Python 从文件读取原始输入
我试图测试一些使用Python 从文件读取原始输入,python,file,stdin,Python,File,Stdin,我试图测试一些使用原始输入的脚本,我有一些预定义的输入文件,其中每一行都是适当的输入。 例如 input.txt: y n y ... 我正试图用file对象替换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
原始输入的脚本,我有一些预定义的输入文件,其中每一行都是适当的输入。
例如
input.txt:
y
n
y
...
我正试图用file对象替换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
我希望调用raw\u input
的函数从文件中获取输入,而不是stdin
。
我有几个这样的文件,我想循环,然后相应地报告。例如,在本例中,我希望con
包含'y'
但显然:
with open("advanced_test1.in") as f:
print f.read()
按预期打印文件内容。执行文件时,使用可以解释更多您想做的工作吗>>@Hackaholic我尝试添加更多详细信息我知道,但我还需要向该函数传递一个变量(该函数调用原始输入
)这就是为什么我想替换stdin
,而不仅仅是使用
python myfile.py < input.txt