SadStudent
SadStudent

Reputation: 297

Making raw_input read from a file

I'm trying to test some script which uses raw_input, I have some predefined input files where each line is the appropriate input. E.g

input.txt:

y
n
y
...

I'm trying to replace sys.stdin with a file object but something is wrong.

with open("input.txt") as f:
    sys.stdin = f
    con = raw_input("aaa") # in reality this is a function which somewhere calls raw_input
    print con # prints nothing 
    sys.stdin = old # saved earlier

I want the function which calls raw_input to get the input from the file rather then the stdin. I have several such files and I want to loop over then and report accordingly. E.g in this example I'd like con to contain 'y'

But obviously:

with open("advanced_test1.in") as f:
    print f.read()

prints the file's content as expected.

Upvotes: 1

Views: 1476

Answers (1)

hjpotter92
hjpotter92

Reputation: 80649

When executing the file, use the < operator as follows:

python myfile.py < input.txt

Upvotes: 3

Related Questions