【问题标题】:Using raw_input after using fileinput使用 fileinput 后​​使用 raw_input
【发布时间】:2014-03-05 15:09:22
【问题描述】:

我有一个 python 脚本,可以从标准输入或文件中读取它的数据。为此,我以下列方式使用fileinput

for line in fileinput.input(args.path):
    read.parseLine(line)

效果很好。但是,在阅读了这个文件/输入之后,我希望能够使用 read 通过标准输入向用户询问一些额外的输入:

data = raw_input("Please enter your data for port {}: ".format(core.getPort()))

这不起作用,因为 raw_input 不断遇到 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

我尝试使用sys.stdin.seek(0) 解决此问题,但返回以下错误:

Traceback (most recent call last):
    File "app_main.py", line 72, in run_toplevel
    File "/usr/local/bin/dvm", line 88, in <module>
    sys.stdin.seek(0)
IOError: [Errno 29] Illegal seek: '<fdopen>'

有没有什么方法可以在使用 fileinput 后​​要求用户输入?

【问题讨论】:

    标签: python python-2.7 stdin


    【解决方案1】:

    fileinput 不会对sys.stdin 做任何事情,除了读取(它明确确保不关闭sys.stdin)。

    但你不能同时使用sys.stdin 作为文件输入 raw_input(); sys.stdin 连接到管道,连接到用户终端。它不能同时连接到两者。并且fileinput 将无限期地从stdin 读取,除非在某个时刻到达文件结尾。

    换句话说,当sys.stdin 未连接到终端时,您不能使用raw_input。您可以使用os.isatty() function 来检测终端是否可用:

    if os.isatty(sys.stdin.fileno()):
        # we have a terminal, I can use `raw_input()`
    

    【讨论】:

    • 我猜不可能在执行时更改标准输入的目的地?
    • @mathsaey:destination 是你的脚本。你不能改变来源,不。这一切都在 Python 运行之前设置好了。
    • 好吧,如果标准输入绑定到管道,是否可以通过其他方式请求用户输入?
    • 命令行开关? stdin 出局了,没有双关语。
    • 就我而言,我可以通过命令行传递 raw_input 请求的信息,所以我可能会走那条路。允许通过 stdin 输入,或通过 stdin 传递文件输入,但不能同时通过两者。无论如何,谢谢你的帮助,如果没有人想出什么,我明天会接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    相关资源
    最近更新 更多