简体   繁体   English

从文件读取raw_input

[英]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. 我正在尝试测试一些使用raw_input脚本,我有一些预定义的输入文件,其中每一行都是适当的输入。 Eg 例如

input.txt: input.txt:

y
n
y
...

I'm trying to replace sys.stdin with a file object but something is wrong. 我正在尝试用文件对象替换sys.stdin ,但是出了点问题。

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 . 我希望调用raw_input的函数从文件而不是stdin I have several such files and I want to loop over then and report accordingly. 我有几个这样的文件,我想遍历然后报告。 Eg in this example I'd like con to contain 'y' 例如,在此示例中,我希望con包含'y'

But obviously: 但显然:

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

prints the file's content as expected. 按预期打印文件的内容。

执行文件时,按如下方式使用<运算符:

python myfile.py < input.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM