问题描述
我有一个非常简单的 Python 3 脚本:
I have a very simple Python 3 script:
f1 = open('a.txt', 'r')
print(f1.readlines())
f2 = open('b.txt', 'r')
print(f2.readlines())
f3 = open('c.txt', 'r')
print(f3.readlines())
f4 = open('d.txt', 'r')
print(f4.readlines())
f1.close()
f2.close()
f3.close()
f4.close()
但它总是说:
IOError: [Errno 32] Broken pipe
我在网上看到了各种复杂的解决方法,但是我直接复制了这段代码,所以我认为是代码有问题,而不是Python的SIGPIPE.
I saw on the internet all the complicated ways to fix this, but I copied this code directly, so I think that there is something wrong with the code and not Python's SIGPIPE.
我正在重定向输出,所以如果上面的脚本被命名为open.py",那么我要运行的命令是:
I am redirecting the output, so if the above script was named "open.py", then my command to run would be:
open.py | othercommand
推荐答案
我没有复现这个问题,但也许这个方法可以解决它:(将一行一行写入 stdout
而不是使用打印
)
I haven't reproduced the issue, but perhaps this method would solve it: (writing line by line to stdout
rather than using print
)
import sys
with open('a.txt', 'r') as f1:
for line in f1:
sys.stdout.write(line)
你能抓住断掉的管道吗?这将文件逐行写入 stdout
直到管道关闭.
import sys, errno
try:
with open('a.txt', 'r') as f1:
for line in f1:
sys.stdout.write(line)
except IOError as e:
if e.errno == errno.EPIPE:
# Handle error
您还需要确保 othercommand
在管道变得太大之前从管道中读取 - https://unix.stackexchange.com/questions/11946/how-big-is-the-pipe-buffer
You also need to make sure that othercommand
is reading from the pipe before it gets too big - https://unix.stackexchange.com/questions/11946/how-big-is-the-pipe-buffer
这篇关于IOError: [Errno 32] 管道破裂:`prog.py |其他命令`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!