Interactive scripts (back on topic for once) [was Re: The "loop and a half"]

Paul Moore p.f.moore at gmail.com
Fri Oct 6 04:48:36 EDT 2017


On 6 October 2017 at 09:36, Peter J. Holzer <hjp-usenet3 at hjp.at> wrote:
> On 2017-10-06 08:09, Steve D'Aprano <steve+python at pearwood.info> wrote:
>> What are the right ways for a Python script to detect these sorts of
>> situations?
>>
>> (1) Standard input is coming from a pipe;
>>
>> (2) Stdin is being read from a file;
>>
>> (3) Stdin is coming from a human at a terminal;
>>
>> I get these. How did I do?
>>
>>
>> # 1 detect input coming from a pipe.
>> import sys
>> import os
>> from stat import S_ISFIFO
>> if S_ISFIFO(os.fstat(0).st_mode):
>>     print("Reading from a pipe")
>>
>>
>> # 2 detect input coming from a regular file.
>> from stat import S_ISREG
>> if S_ISREG(os.fstat(0).st_mode):
>>     print("Reading from a file.")
>>
>> # 3 detect a terminal, hopefully with a human typing at it
>> if os.isatty(0):
>>     print("Oy noddy, wake up and type something, I'm waiting for you!")
>
> I'd do it the same way.
>
>> I feel a bit weird about using the magic constant 0 here. Is that guaranteed
>> to be stdin on all platforms?
>
> It is guaranteed on POSIX compatible OSs. I think it is also guaranteed
> on Windows, Don't know about VMS or the IBM OSs.

All of these work on Windows, I just tested. Which surprised me, as I
thought things like S_ISFIFO were Unix specific. Today I learned...
(I'd probably still use sys.stdin.fileno() as it's more
self-documenting).

Paul



More information about the Python-list mailing list