gpt4 book ai didi

python - "is"报告子进程通信错误()

转载 作者:IT王子 更新时间:2023-10-29 00:50:55 26 4
gpt4 key购买 nike

我正在使用以下函数在 Python 中运行命令:

def run_proc(cmd):
child = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = child.communicate()
returncode = child.returncode
return stdout, stderr, returncode

它一直运行良好,但现在我正在尝试使用 yes 程序将输出通过管道传输到标准输入。我尝试运行的命令如下:

yes '' | apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" dist-upgrade

但我相信它可以用一般示例代替,例如:

yes | head -3 | cat

我的问题是,如果我尝试运行任何包含 yes | 的命令,上面的 subprocess.Popen 将包含错误消息:

yes: standard output: Broken pipe
yes: write error

对我来说,管道似乎仍然有效,从 yes | 可以看出头-3 | cat 的回答:y y y

我有以下问题:

  1. yes 管道是否仍然有效,即使 yes 报告错误?
  2. 我该如何解决?

最佳答案

问题是 subprocess 模块 before Python 3.2+ doesn't restore SIGPIPE signal handler to default action .这就是为什么您会收到 EPIPE 写入错误的原因。

在 Python 3.2+ 中

>>> from subprocess import check_output
>>> check_output("yes | head -3", shell=True)
b'y\ny\ny\n'

yeshead 退出时被 SIGPIPE 杀死。

在 Python 2 中:

>>> from subprocess import check_output
>>> check_output("yes | head -3", shell=True)
yes: standard output: Broken pipe
yes: write error
'y\ny\ny\n'

EPIPE 写入错误。忽略错误是安全的。 It communicates the same information as SIGPIPE .

要解决此问题,您可以使用 preexec_fn 参数在 Python 2 中模拟 restore_signals:

>>> from subprocess import check_output
>>> import signal
>>> def restore_signals(): # from http://hg.python.org/cpython/rev/768722b2ae0a/
... signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')
... for sig in signals:
... if hasattr(signal, sig):
... signal.signal(getattr(signal, sig), signal.SIG_DFL)
...
>>> check_output("yes | head -3", shell=True, preexec_fn=restore_signals)
'y\ny\ny\n'

关于python - "is"报告子进程通信错误(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22077881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com