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?

Thanks,

Will.

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

#!/usr/bin/python
#
# hail - heads and tails

import sys, os, getopt

def hail(file,headlines=10,taillines=10):
    lines = file.readlines()
    sys.stdout.writelines(lines[:headlines])
    sys.stdout.writelines(lines[taillines:])

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():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "t:b:h",
['top=','bottom=','help'])
    except getopt.GetoptError:
        useage()
        sys.exit(2)
    for o,a in opts:
        if o in ("-t", "--top"):
            toplines = a
        if o in ("-b", "--bottom"):
            bottomlines = a
        if o in ("-h", "--help"):
            useage()
            sys.exit()
    if len(args) == 1 and os.path.exists(str(args[0])):
        file = (str(args[0]))
    # else:
    #   file = sys.stdin
    hail(file,headlines=toplines,taillines=bottomlines)

if __name__ == "__main__":
    main()



More information about the Python-list mailing list