IOError:[Errno 32]管道损坏:Python [英] IOError: [Errno 32] Broken pipe: Python

查看:203
本文介绍了IOError:[Errno 32]管道损坏:Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的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而不是使用print)

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,直到关闭管道为止.


You could catch the broken pipe? This writes the file to stdout line by line until the pipe is closed.

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在管道过大之前正在从管道读取-

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]管道损坏:Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆