views:

132

answers:

4

I'm trying to write a python script which follows the common unix command line pattern of accepting input from stdin if no file name is given. This is what I've been using:

if __name__ == "__main__":
    if len(sys.argv) > 1:
        stream = open(sys.argv[1])
    else:
        stream = sys.stdin

Is there a more pythonic way to do that?

+4  A: 

similar but one-line solution

stream = sys.argv[1] if len(sys.argv)>1 else sys.stdin
luc
Won't `len(sys.argv)` *always* be at least one (the script name is `argv[0]`)?
Steve Losh
Oups. I've corrected that
luc
+10  A: 

The fileinput module is perfect for this.

Ned Batchelder
Yep, that's exactly what I wanted. Thanks!For bonus points do you have any tips on how nicely it plays with [optparse](http://docs.python.org/library/optparse.html)?
Paul Huff
Huh I guess no markdown in comments?
Paul Huff
A: 

I would suggest you make it more unixy instead:

if len(sys.argv) > 1:
    sys.stdin = open(sys.argv[1])
Matt Joiner
-1: this makes sys.stdin change semantics (see the documentation for the sys module), and breaks expectations. This therefore makes the code less legible (someone who misses the change of sys.stdin would infer that the program does not read an input file argument).
EOL
+2  A: 

how about this one?

stream=sys.argv[1:] and open(sys.argv[1]) or sys.stdin
S.Mark