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

Thomas Jollans tjol at tjol.eu
Fri Oct 6 08:31:26 EDT 2017


On 2017-10-06 12:33, Ben Bacarisse wrote:
> 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!

stdin is ALWAYS fileno 0, whether the input is attached to a tty or not.
The only situation where sys.stdin.fileno() != 0 is when sys.stdin has
been reassigned from within python.

$ python -c 'import sys; print(sys.stdin.fileno())' < /dev/zero
0

This should be true for all platforms, or at least all platforms python
supports.


> 
> <snip>
> 


-- 
Thomas Jollans



More information about the Python-list mailing list