【发布时间】:2015-02-02 18:19:20
【问题描述】:
我想运行一个 python 3 脚本,通过标准输入或手动输入数据给它一个文件。
例如假设我想用一行打印输入的内容。名为app.py 的脚本如下所示:
from sys import stdin
print("Input says:"+stdin.readline())
然后,我可以通过以下两种方式运行它:
1.将文件作为标准输入传递
python app.py < input.txt
2。提示用户输入
python app.py
我的问题是,在这两种情况下,在阅读标准输入后,我想提示用户输入一些额外的数据。按照前面提到的示例,它将是:
from sys import stdin
print("Input says:"+stdin.readline())
print("Did you like that? (Yes/No)")
ans = input() # This line is the issue!
if( ans == "Yes"):
print("You liked it!")
上面注释的行非常适用于案例 2,但对于案例 1,它会抛出 EOFError: EOF when reading a line 错误,因为它试图从文件中读取。
我想知道在那条线之前我是否可以做类似的事情
sys.stdin = SOMETHING
其中 SOMETHING 代表 Windows 控制台输入。我认为如果我能做到这一点,那么这两种情况都会正常工作。
【问题讨论】:
-
您可以通过
win32consoleapi 访问控制台。 -
试试
CON或CONIN$。可能会起作用,具体取决于 Python 究竟做了什么。 -
你的问题不清楚;您想从 console 提示一些输入,即使您提供了一个文件为
sys.stdin。
标签: python windows python-3.x input stdin