In Python, as with most languages, STDIN is treated like a file. You can read from it any time, but knowing what kind of file it is lets us know if someone passed us something via STDIN or if we are going to prompt them for it.
import os, sys
if os.isatty(file.fileno(sys.stdin)):
print "Reading list from STDIN."
print "Enter your list. Press ^D to continue, ^C to quit."
my_list = sys.stdin.readlines()
else:
print "Thank you for passing me a list through a pipe."
my_list = sys.stdin.readlines()
Now lets try it two ways:
First, pass it some stuff:
echo mother sister father brother | ./myapp.py
Then try it plain:
./myapp.py
Did you find this post useful or have questions or comments? Please let me know!
instead of:
os.isatty(file.fileno(sys.stdin))
use:
sys.stdin.isatty()
It is probably moot, but the first version threw a TypeError when run within IDLE.
Thanks! I’ll test and update the post.