Python 在使用fileinput之后使用原始输入
我有一个python脚本,可以从stdin或文件中读取数据。为此,我以以下方式使用:Python 在使用fileinput之后使用原始输入,python,python-2.7,stdin,Python,Python 2.7,Stdin,我有一个python脚本,可以从stdin或文件中读取数据。为此,我以以下方式使用: for line in fileinput.input(args.path): read.parseLine(line) 这很好用。但是,在阅读此文件/输入后,我希望能够通过stdin使用read: data = raw_input("Please enter your data for port {}: ".format(core.getPort())) 这不起作用,因为原始输入不断遇到EOF P
for line in fileinput.input(args.path):
read.parseLine(line)
这很好用。但是,在阅读此文件/输入后,我希望能够通过stdin使用read:
data = raw_input("Please enter your data for port {}: ".format(core.getPort()))
这不起作用,因为原始输入不断遇到EOF
Please enter your data for port 0: Traceback (most recent call last):
File "app_main.py", line 72, in run_toplevel
File "/usr/local/bin/dvm", line 98, in <module>
data = raw_input("Please enter your data for port {}: ".format(core.getPort()))
EOFError
在使用fileinput之后,是否有任何方法要求用户输入
fileinput
除了读取之外,对sys.stdin
没有任何作用(它明确确保不关闭sys.stdin
)
但是不能同时将sys.stdin
用作文件输入和原始输入();sys.stdin
连接到管道,或者连接到用户终端。它不能同时附加到两个。而fileinput
将无限期地从stdin
读取,除非在某个点到达文件末尾
换句话说,当sys.stdin
未连接到终端时,不能使用raw\u input
。您可以使用来检测终端是否可用:
if os.isatty(sys.stdin.fileno()):
# we have a terminal, I can use `raw_input()`
我猜在执行时改变stdin的目标是不可能的?@mathsaey:目标是你的脚本。不能更改源代码。在Python运行之前就已经设置好了。好的,如果stdin绑定到管道,是否可以以其他方式请求用户输入?也许可以使用命令行开关stdin
已退出,没有双关语的意思。在我的情况下,我可以通过命令行传递原始输入请求的信息,因此我可能会选择该路线。允许通过stdin输入或通过stdin传递fileinput,但不能同时允许两者。不管怎样,谢谢你的帮助,如果没有人想出什么主意,我明天会接受的。
if os.isatty(sys.stdin.fileno()):
# we have a terminal, I can use `raw_input()`