python 子进程: "write error: Broken pipe"

标签 python subprocess popen

我在管道传输一个简单的 subprocess.Popen 时遇到问题。

代码:

import subprocess
cmd = 'cat file | sort -g -k3 | head -20 | cut -f2,3' % (pattern,file)
p = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
for line in p.stdout:
    print(line.decode().strip())

文件的输出长度约为 1000 行:

...
sort: write failed: standard output: Broken pipe
sort: write error

文件的输出长度 >241 行:

...
sort: fflush failed: standard output: Broken pipe
sort: write error

<241 行长度的文件输出没问题。

我一直在疯狂地阅读文档和谷歌搜索,但我遗漏了一些关于子进程模块的基本知识……可能与缓冲区有关。我试过 p.stdout.flush() 并调整缓冲区大小和 p.wait()。我试图用“sleep 20;”之类的命令重现这一点。 cat moderatefile' 但这似乎运行没有错误。

最佳答案

来自 subprocess 上的食谱文档:

# To replace shell pipeline like output=`dmesg | grep hda`
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

关于 python 子进程: "write error: Broken pipe",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4106565/

相关文章:

python - Pyzmq - 将消息发送到 STREAM 套接字

python - 计算文件中所有可能的长度为 n 的子字符串? (不包括空格)

python - 使用不平衡学习进行过采样后训练的形状输出

Python 3.4.3 subprocess.Popen 在没有管道的情况下获取命令输出?

Python subprocess.call bash 别名

python - 解析预期输出

Python - Mechanize/请求获取标题

python - 在subprocess.Popen中,bufsize适用于哪个文件?

python - 保持通向进程的管道打开

c - fgets 中的段错误,试图在 c 程序中运行 shell 命令