【问题标题】:Python piping on Windows: Why does this not work?Windows 上的 Python 管道:为什么这不起作用?
【发布时间】:2010-10-02 18:44:53
【问题描述】:

我正在尝试这样的事情

输出.py

print "Hello"

输入.py

greeting = raw_input("Give me the greeting. ")
print "The greeting is:", greeting

在命令行

Output.py | Input.py

但它返回一个EOFError。谁能告诉我我做错了什么?

感谢您的帮助。

编辑
Patrick Harrington solution 有效,但我不知道为什么...

【问题讨论】:

  • 也就是我用 input(..) 代替 raw_input(..)
  • 我已经更新了我的答案,以解释为什么我和帕特里克提出的解决方案有效而原来的解决方案无效。
  • 使用替代解决方案(添加注册表项)再次更新,以避免在调用 input.py 时需要指定 python 可执行文件

标签: python windows piping


【解决方案1】:

我在我的 Windows 机器上测试过,如果你指定 Python exe,它就可以工作:

C:\>C:\Python25\python.exe output.py | C:\Python25\python.exe input.py
Give me the greeting. The greeting is: hello

但如果直接运行命令,我也会收到 EOFError:

output.py | input.py 

我不确定这是为什么,我仍在研究这个,但至少现在应该为您提供一种解决方法。它可能与为 .py 文件调用文件处理程序的方式有关。

更新:嗯,你知道什么。看起来这实际上是 Windows 中的一个错误,从文件关联启动时,stdin/stdout 重定向可能无法正常工作。因此,解决方法正如我和 Patrick 所指出的,您需要指定“python”将运行 input.py,否则它不会将 stdout 从 output.py 正确重定向到 input.py 的 stdin。

参考

http://mail.python.org/pipermail/python-bugs-list/2004-August/024923.html

http://support.microsoft.com/default.aspx?kbid=321788

更新 2

要更改此行为并使 Windows 管道按预期工作以进行 stdin/stdout 重定向,您可以将此值添加到注册表(在我的机器上测试并验证它是否按预期工作)。

  1. 启动注册表编辑器。
  2. 在注册表中找到并单击以下键:

    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer

  3. 在编辑菜单上,单击添加值,然后添加以下内容 注册表值:

    值名称:InheritConsoleHandles
    数据类型:REG_DWORD
    基数:十进制
    数值数据:1

  4. 退出注册表编辑器。

【讨论】:

  • 值得一提的是,现在您可以将InheritConsoleHandles 值添加到Windows 注册表以使用output.py | input.py,如链接的microsoft.com 页面中所述。
【解决方案2】:

改成:

Output.py | python Input.py

输出将是:

给我打招呼。问候语是:你好

【讨论】:

    【解决方案3】:

    这就是您收到 EOFError 的原因(来自 raw_input 的文档):

    然后该函数从 输入,将其转换为字符串 (剥离尾随换行符),和 返回那个。读取 EOF 时, 引发了 EOFError。

    http://docs.python.org/library/functions.html?highlight=raw_input#raw_input

    您可能想要使用 sys.stdin,它提供了一个文件对象,您可以从中使用 read、readlines 方法。

    import sys
    for greeting_line in sys.stdin.readlines():
        print "The greeting is:", greeting_line.strip()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-03
      • 2011-10-13
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 2016-06-19
      相关资源
      最近更新 更多