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?

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
Paul Huff
  • 173
  • 5

4 Answers4

10

The fileinput module is perfect for this.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 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 Nov 20 '09 at 14:48
5

similar but one-line solution

stream = sys.argv[1] if len(sys.argv)>1 else sys.stdin
luc
  • 41,928
  • 25
  • 127
  • 172
2

how about this one?

stream=sys.argv[1:] and open(sys.argv[1]) or sys.stdin
YOU
  • 120,166
  • 34
  • 186
  • 219
0

I would suggest you make it more unixy instead:

if len(sys.argv) > 1:
    sys.stdin = open(sys.argv[1])
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
  • -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). – Eric O. Lebigot Nov 20 '09 at 15:01