SQ101
SQ101

Reputation: 13

How to combine file input from the command line and user input

I'm having trouble prompting the user for input after I have already read a file from the command line. My code looks something like this but I get an EOFError every time. Am I missing something? My code:

import sys
file = sys.stdin.read().splitlines()
print (file)
name = input("Input your name: ")
print (name)

Here is what I put into the command line for these lines:

python3 tester.py < example_file.txt
['my file']
Input your name: Traceback (most recent call last):
File "tester.py", line 4, in <module>
name = input("Input your name: ")
EOFError: EOF when reading a line

In this case, I believe I get out of the sys.stdin.read().splitlines() line given that it correctly prints out the information in file. However, once the line containing input() is executed, I am not prompted to input anything and I get an error without pausing to input like normal.

Upvotes: 1

Views: 245

Answers (1)

dawg
dawg

Reputation: 104092

You can use the fileinput module to handle multiple streams a little easier.

import fileinput

t_list=[line for line in fileinput.input()]
print(t_list)

name=input('name? ')
print(name)

Then run with the file name, not the string contents of the file:

$ python3 test.py file
['my file\n']
name? bob
bob

Upvotes: 1

Related Questions