On Fri, Oct 6, 2017 at 7:09 PM, Steve D'Aprano
<steve+pyt...@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).

> 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()?

I believe it is. At any rate, any system that doesn't have 0/1/2 =
in/out/err is likely to have far more differences than this sort of
thing will cope with, so you won't be able to support it that easily.
So go ahead and assume.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to