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

Steve D'Aprano steve+python at pearwood.info
Fri Oct 6 04:09:16 EDT 2017


On Fri, 6 Oct 2017 12:37 pm, Ben Bacarisse wrote:

>> But in fairness, if the author of the `sort` command had a commitment to
>> friendliness in their programs, they could have `sort` only print a message
>> when it is reading from stdin and writing to stdout,
> 
> I think you mean "when reading from a terminal".  In the example given
> sort /is/ reading from stdin and writing to stdout.

Indeed I did, it was a slip of the brain.


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



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list