tags:

views:

35

answers:

2

I want my code to be able to accept input from a file AND stdin. What's the construct to do it?

I mean a unifying construct that implies

file1 = sys.stdin

and

file1 = fileinput.input(sys.argv[1])
+2  A: 
import fileinput
for line in fileinput.input():
    print line
ghostdog74
+1  A: 

"Unifying construct" sounds like you want to be able to access either a file provided as an argument or sys.stdin through one variable, so you can just tell functions to get a line from that thing. Luckily, sys.stdin is just another File object, so you have exactly the same functionality with both and it's as easy as a try/except block:

try:
  from sys import argv
  file1 = open(argv[1])
except:
  from sys import stdin
  file1 = stdin

You'll get sys.stdin if argv[1] is out of range (IndexError) or can't be opened (IOError).

If you just want to concatenate the two, use file1 = sys.argv[1].open().read() + sys.stdin.read()

echoback