On 2017-10-06 08:09, 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? > > > # 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. > Or should I be using sys.stdin.fileno()? I'm not conviced that this is much more portable: A platform where stdin doesn't use file descriptor 0 under the hood might not even use simple integers as file descriptors at all. hp -- _ | Peter J. Holzer | Fluch der elektronischen Textverarbeitung: |_|_) | | Man feilt solange an seinen Text um, bis | | | h...@hjp.at | die Satzbestandteile des Satzes nicht mehr __/ | http://www.hjp.at/ | zusammenpaĆt. -- Ralph Babel -- https://mail.python.org/mailman/listinfo/python-list