Testing for the presence of input from stdin.

Will McDonald wmcdonald at gmail.com
Mon Jan 23 06:38:05 EST 2006

Hi all.

I'm writing a little script that operates on either stdin or a file
specified on the command line when run. I'm trying to handle the
situation where the script's run without any input gracefully but
can't think how to test for stdin.

I can test for a file argument on the command line using getopt and
validate its existence with os.path.exists. If it doesn't I can print
the useage.

I can get the script to behave as expected when content's piped to it
using sys.stdin but I'd like to know that there's data coming from
stdin or fail and print the useage again. Is there a simple way to
achieve this?



Here's what I've got so far...

# hail - heads and tails

import sys, os, getopt

def hail(file,headlines=10,taillines=10):
    lines = file.readlines()

def useage():
    print "Useage: hail [OPTION] [FILE]"
    print "  -t, --top      # lines from top (default 10)"
    print "  -b, --bottom   # lines from bottom (default 10)"
    print "  -h, --help     display this help and exit"

def main():
        opts, args = getopt.getopt(sys.argv[1:], "t:b:h",
    except getopt.GetoptError:
    for o,a in opts:
        if o in ("-t", "--top"):
            toplines = a
        if o in ("-b", "--bottom"):
            bottomlines = a
        if o in ("-h", "--help"):
    if len(args) == 1 and os.path.exists(str(args[0])):
        file = (str(args[0]))
    # else:
    #   file = sys.stdin

if __name__ == "__main__":

More information about the Python-list mailing list