5

我在 Windows XP 上。这似乎会影响任何进程,但我将使用 Python3.2 来演示它。一个脚本,“filter.py”:

import sys
for line in sys.stdin:
    print(line)

像这样运行它:

echo hello | filter.py

像这样中断:

Traceback (most recent call last):
  File "F:\Documents and Settings\jhartley\docs\projects\filtercwd\filter.py", line 3, in <module>
    for line in sys.stdin:
TypeError: 'NoneType' object is not iterable

果然,添加打印以发现 sys.stdin 的值报告它是 None (和 NoneType。)

或者,像这样运行它:

echo hello | python filter.py

(显式调用python)工作得很好。

我的 .py 文件使用 assoc 和 ftype 机制(Windows 关联特定文件扩展名以使用特定程序执行的方式)使用 Python 执行:

> assoc .py
.py=Python.File
> ftype Python.File
Python.File="F:\Python32\python.exe" "%1" %*

(这是我路径上最重要的“python.exe”)

更新:这不是 Python 的东西。如果我创建 filter.sh,使用 cygwin bash 运行,也会发生同样的事情。显式运行'echo hello | bash filter.sh' 工作正常,但 'echo hello | filter.sh' 通过 assoc 和 ftype 机制使用 bash 执行 filter.sh,失败并显示“/dev/stdin:没有这样的文件或目录”。

所以我必须将这个显式的“python”添加到我的所有命令行中吗?另外,我很好奇它为什么会坏。这只是我机器的一些特性,还是其他人也看到了?

4

1 回答 1

1

echo在用什么?您的路径上是否有一个 UNIX 风格的echo实用程序,或者您只是在使用 Microsoft 的实用程序(它不能满足您的要求)?如果echo on在命令提示符下键入会发生什么?

我在 Windows 7 中运行,无法重现。echo我的路径上有一个 UNIX 风格的实用程序。我已经安装了 ruby​​ 1.9.2并在以下位置编写了小程序test.rb

while s = $stdin.gets
  print s
end

当我键入以下任何命令时,程序就会运行:

  1. test.rb
  2. ruby test.rb
  3. echo hello | test.rb
  4. echo hello | ruby test.rb

命令 1 和 2 的行为相同。命令 3 和 4 的行为相同。一切都如我所料。

编辑1: 这是我运行的一些命令:

C:\Users\David\Documents\scraps\test_ruby>ls
test.rb

C:\Users\David\Documents\scraps\test_ruby>assoc .rb
File association not found for extension .rb

C:\Users\David\Documents\scraps\test_ruby>echo hi | test.rb
hi

我对 ftype 了解不多,但也许你应该在你的系统上安装 ruby​​,看看我的示例程序是否适合你。

于 2011-07-10T16:34:28.250 回答