【问题标题】:Making raw_input read from a file从文件中读取 raw_input
【发布时间】:2014-11-01 12:08:39
【问题描述】:

我正在尝试测试一些使用raw_input 的脚本,我有一些预定义的输入文件,其中每一行都是适当的输入。 例如

输入.txt:

y
n
y
...

我正在尝试用文件对象替换 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_input 的函数从文件而不是stdin 中获取输入。 我有几个这样的文件,然后我想循环并相应地报告。例如,在此示例中,我希望 con 包含 'y'

但显然:

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

按预期打印文件的内容。

【问题讨论】:

  • 你能解释更多你想做的事情吗>>
  • @Hackaholic 我尝试添加更多细节

标签: python file stdin


【解决方案1】:

执行文件时,使用<操作符,如下:

python myfile.py < input.txt

【讨论】:

  • 我知道这一点,但我还需要将变量传递给该函数(调用 raw_input),这就是为什么我要替换 stdin 而不仅仅是使用 &lt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
相关资源
最近更新 更多