HOW TO detect STDIN with Python

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()
    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 | ./

Then try it plain:

Did you find this post useful or have questions or comments? Please let me know!

This entry was posted in How Tos, Programming, python. Bookmark the permalink.

2 Responses to HOW TO detect STDIN with Python

  1. Rufus says:

    instead of:

    It is probably moot, but the first version threw a TypeError when run within IDLE.

  2. admin says:

    Thanks! I’ll test and update the post.

Leave a Reply

Your email address will not be published. Required fields are marked *