我在管道传输一个简单的 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/