1

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])
0

2 Answers 2

6
import fileinput
for line in fileinput.input():
    print line
Sign up to request clarification or add additional context in comments.

1 Comment

This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. -- docs.python.org/2/library/fileinput.html
0

"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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.