gpt4 book ai didi

python - 为什么 `subprocess.check_call(..., stderr=sys.stdout)` 在 Python 2.6 中失败?

转载 作者:太空狗 更新时间:2023-10-29 21:45:41 24 4
gpt4 key购买 nike

Python 2.6.9 (unknown, Mar  7 2016, 11:15:18) 
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import subprocess
>>> subprocess.check_call(['echo', 'hi'], stderr=sys.stdout)
echo: write error: Bad file descriptor
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/subprocess.py", line 488, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['echo', 'hi']' returned non-zero exit status 1

此命令 subprocess.check_call(['echo', 'hi'], stderr=sys.stdout) 在 Python 2.7 和 Python 3 中工作得很好。Python 2.6 有什么不同之处?

最佳答案

讨论了该错误 here :

Transcript to reproduce in Python 2.6.5:

>>> import subprocess, sys
>>> subprocess.call(('echo', 'foo'), stderr=sys.stdout)
echo: write: Bad file descriptor
1
>>>

Expected behavior:

>>> import subprocess, sys
>>> subprocess.call(('echo', 'foo'), stderr=sys.stdout)
foo
0
>>>

This happens because we've asked the child's stderr to be redirected, but not its stdout. So in _execute_child, errwrite is 1 while c2pwrite is None. So fd 1 (errwrite) correctly gets duped to 2. But then, since errwrite is not None and it's not in (p2cread, c2pwrite, 2), the child closes fd 1.

The equivalent thing happens if you supply stdout=sys.stderr and the child attempts to write to its stderr.

I've attached a patch to fix this. It simply adds 2 and 2 to the list of fds not to close for c2pwrite and errwrite, respectively.

This patch is against the 2.6.5 release.

There is also a workaround, in case anyone else is affected by this bug before a fix has been released:

>>> import os, subprocess, sys
>>> subprocess.call(('echo', 'foo'), stderr=os.dup(sys.stdout.fileno()))
foo
0
>>>

它在 2.7 中用这个 patch 修复了在相关的issue .

关于python - 为什么 `subprocess.check_call(..., stderr=sys.stdout)` 在 Python 2.6 中失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36311719/

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