断管错误 Python 子流程

Broken-pipe Error Python subprocess

我正在尝试启动多个 bash 例程 从基于 GUI 的软件。我面临的问题是管道问题。 这里测试 bash-script (bashScriptTest.sh):

#!/bin/bash
#---------- Working
ls | sort | grep d > testFile.txt
cat testFile.txt
#---------- NOT working
echo $RANDOM > testFile2.txt
for i in `seq 1 15000`; do
    echo $RANDOM >> testFile2.txt
done
awk '{print }' testFile2.txt | sort -g | head -1

这里是创建错误的 python 脚本:

import subprocess
#
with open('log.txt','w') as outfile:
    CLEAN=subprocess.Popen("./bashScriptTest.sh", stdout=outfile, stderr=outfile)
    print CLEAN.pid
    OUTSEE=subprocess.Popen(['x-terminal-emulator', '-e','tail -f '+outfile.name])

从运行脚本中可以看出,python脚本遇到了Broken-pipe错误 不是在前三个管道(第一行)中,而是在 awk 完成大量工作之后。 我需要在 bash 中管理大量例程和子例程 并且使用 shell==True 标志也不会改变任何事情。 我试着用最 pythonic 的方式写所有的东西,但不幸的是没有 有机会我可以重写 python 中的所有管道步骤。 另一件要提到的事情是,如果您在终端内测试 bash 脚本 一切正常。 任何帮助将非常感激。提前致谢!

编辑 1:

包含错误的日志文件显示:

bashScriptTest.sh
log.txt
stack.txt
testFile2.txt
test.py
3
sort: write failed: standard output: Broken pipe
sort: write error

好吧,这有点晦涩,但碰巧我 运行 在研究 question on the python-tutor mailing list 前一段时间遇到了类似的问题。

当 运行 您的脚本通过子进程模块(在 python 中)与直接 bash 时,您看到不同行为的原因是 python 覆盖对于所有子进程(全局),SIGPIPE 的配置为 SIG_IGN(忽略)。

执行以下管道时...

awk '{print }' testFile2.txt | sort -g | head -1
由于 -1 标志,

... head 将在从 sort 命令打印第一行标准输出后退出。当 sort 命令尝试将更多行写入其标准输出时,将引发 SIGPIPE。

SIGPIPE的默认动作;例如,当管道在 shell 中执行时,例如 bash;是终止排序命令。

如前所述,python 使用 SIG_IGN(忽略)覆盖了默认操作,因此我们最终得到了这种奇怪且有些莫名其妙的行为。


这一切都很好,但您可能想知道现在该做什么?这取决于您使用的 python 版本 ...

对于 Python 3.2 及更高版本,您已经设置好了。 subprocess.Popen in 3.2新增restore_signals参数,默认为True,有效解决问题,无需进一步操作。

对于以前的版本,您可以为 subprocess.Popenpreexec_fn 参数提供一个可调用对象,如 ...

import signal
def default_sigpipe():
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)

# ...

with open('log.txt','w') as outfile:
    CLEAN=subprocess.Popen("./bashScriptTest.sh", 
                           stdout=outfile, stderr=outfile
                           preexec_fn=default_sigpipe)

希望对您有所帮助!

编辑: 可能应该注意您的程序实际上运行正常,AFAICT,原样。您只是看到了直接在 shell 中执行脚本时通常不会看到的其他错误消息(出于上述原因)。

另请参阅: