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

Ben Bacarisse ben.usenet at bsb.me.uk
Fri Oct 6 06:33:22 EDT 2017


Chris Angelico <rosuav at gmail.com> writes:

> On Fri, Oct 6, 2017 at 7:09 PM, 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?
>>
>> # 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!")
>
> This ought to be the only one that matters. It's the closest thing you
> have to "we're working in interactive mode". Generally speaking, you
> shouldn't care about the difference between a pipe and a file; and
> remember, you can have stdin be anything else, too (eg a Unix or TCP
> socket).

Yes.  I'd say the key differences is whether the input is seekable or
not.  A program might legitimately choose different algorithms based on
that property of the input, but whether it's an actual file or an actual
pipe is less likely to be interesting.

>> I feel a bit weird about using the magic constant 0 here. Is that guaranteed
>> to be stdin on all platforms? Or should I be using
>> sys.stdin.fileno()?

A general solution to the (rather odd) complaint about silent waiting
should really check any input fileno to see if a prompt is needed.  You
could argue, though, that anyone who's re-arranged a program's input so
that some non-zero input fileno is attached to a terminal won't need the
prompt!

<snip>
-- 
Ben.



More information about the Python-list mailing list