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])
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
“Unifying construct” sounds like you want to be able to access either a file provided as an argument or
sys.stdinthrough one variable, so you can just tell functions to get a line from that thing. Luckily,sys.stdinis just another File object, so you have exactly the same functionality with both and it’s as easy as a try/except block:You’ll get
sys.stdinif 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()