subprocess.check_output() 似乎不存在(Python 2.6.5)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4814970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
subprocess.check_output() doesn't seem to exist (Python 2.6.5)
提问by robintw
I've been reading the Python documentation about the subprocess module (see here) and it talks about a subprocess.check_output()command which seems to be exactly what I need.
我一直在阅读有关 subprocess 模块的 Python 文档(请参阅此处),它谈到了一个subprocess.check_output()似乎正是我需要的命令。
However, when I try and use it I get an error that it doesn't exist, and when I run dir(subprocess)it is not listed.
但是,当我尝试使用它时,我收到一个错误,指出它不存在,并且当我运行dir(subprocess)它时未列出。
I am running Python 2.6.5, and the code I have used is below:
我正在运行 Python 2.6.5,我使用的代码如下:
import subprocess
subprocess.check_output(["ls", "-l", "/dev/null"])
Does anyone have any idea why this is happening?
有谁知道为什么会这样?
采纳答案by user225312
It was introduced in 2.7 See the docs.
它是在 2.7 中引入的,请参阅文档。
Use subprocess.Popenif you want the output:
如果需要输出,请使用subprocess.Popen:
>>> import subprocess
>>> output = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0]
回答by technicalbloke
IFit's used heavily in the code you want to run but that code doesn't have to be maintained long-term (or you need a quick fix irrespective of potential maintenance headaches in the future) then you could duck punch (aka monkey patch) it in wherever subprocess is imported...
如果它在您要运行的代码中大量使用,但该代码不必长期维护(或者您需要快速修复,而不管将来可能出现维护问题),那么您可以躲避(又名猴子补丁)它在任何导入子流程的地方...
Just lift the code from 2.7 and insert it thusly...
只需从 2.7 中提取代码并插入它...
import subprocess
if "check_output" not in dir( subprocess ): # duck punch it in!
def f(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd)
return output
subprocess.check_output = f
Minor fidgeting may be required.
可能需要轻微的坐立不安。
Do bear in mind though the onus is on you to maintain dirty little backports like this. If bugs are discovered and corrected in the latest python then you a) have to notice that and b) update your version if you want to stay secure. Also, overriding & defining internal functions yourself is the next guy's worst nightmare, especially when the next guy is YOU several years down the line and you've forgot all about the grody hacks you did last time! In summary: it's very rarely a good idea.
请记住,尽管您有责任维护这样的肮脏小后端。如果在最新的 python 中发现并纠正了错误,那么您 a) 必须注意这一点,并且 b) 如果您想保持安全,请更新您的版本。此外,自己覆盖和定义内部函数是下一个人最糟糕的噩梦,尤其是当下一个人是你几年后,你已经忘记了你上次所做的所有骇人听闻的黑客攻击!总而言之:这很少是一个好主意。
回答by keen
Thanks to the monkey patch suggestion (and my attempts failing - but we were consuming CalledProcessError output, so needed to monkey patch that)
感谢猴子补丁建议(我的尝试失败了 - 但我们正在消耗 CalledProcessError 输出,所以需要对它进行猴子补丁)
found a working 2.6 patch here: http://pydoc.net/Python/pep8radius/0.9.0/pep8radius.shell/
在这里找到了一个有效的 2.6 补丁:http: //pydoc.net/Python/pep8radius/0.9.0/pep8radius.shell/
"""Note: We also monkey-patch subprocess for python 2.6 to
give feature parity with later versions.
"""
try:
from subprocess import STDOUT, check_output, CalledProcessError
except ImportError: # pragma: no cover
# python 2.6 doesn't include check_output
# monkey patch it in!
import subprocess
STDOUT = subprocess.STDOUT
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs: # pragma: no cover
raise ValueError('stdout argument not allowed, '
'it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE,
*popenargs, **kwargs)
output, _ = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd,
output=output)
return output
subprocess.check_output = check_output
# overwrite CalledProcessError due to `output`
# keyword not being available (in 2.6)
class CalledProcessError(Exception):
def __init__(self, returncode, cmd, output=None):
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (
self.cmd, self.returncode)
subprocess.CalledProcessError = CalledProcessError

