在Python中从stdin读取时出现坏管道文件描述符

2 投票
1 回答
4321 浏览
提问于 2025-04-15 12:33

这是一个与这个问题重复的帖子。请投票关闭。

考虑一下在Windows命令行中的情况。

scriptA.py | scriptB.py

在scriptA.py中:

sys.stdout.write( "hello" )

在scriptB.py中:

print sys.stdin.read()

这会产生以下错误:

c:\> scriptA.py | scriptB.py
close failed: [Errno 22] Invalid argument
Traceback (most recent call last):
  File "c:\scriptB.py", line 20, in <module>
    print sys.stdin.read()
IOError: [Errno 9] Bad file descriptor

“关闭失败”的信息似乎是从执行scriptA.py时出现的。

无论我使用sys.stdin.read()、sys.stdin.read(1)、sys.stdin.readlines()等,结果都是一样的。

到底出了什么问题?

这是一个与这个问题重复的帖子。请投票关闭。

1 个回答

7

看起来,当你从文件关联启动程序时,标准输入(stdin)和标准输出(stdout)的重定向是无效的。这并不是Python特有的问题,而是win32的命令提示符(cmd.exe)引起的一个问题。

详情请见:http://mail.python.org/pipermail/python-bugs-list/2004-August/024920.html

撰写回答