在Python 2.6.5中,“subprocess.check_output()”似乎不存在

2024-04-25 04:53:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在阅读关于子流程模块的Python文档(参见here),它谈到了一个subprocess.check_output()命令,这似乎正是我所需要的。

但是,当我尝试使用它时,我得到一个错误,即它不存在,并且当我运行dir(subprocess)时,它没有列出。

我运行的是Python2.6.5,我使用的代码如下:

import subprocess
subprocess.check_output(["ls", "-l", "/dev/null"])

有人知道为什么会这样吗?


Tags: 模块代码文档devimport命令outputhere
3条回答

多亏了monkey补丁的建议(我的尝试失败了——但是我们正在消耗CalledProcessError输出,所以需要对其进行monkey补丁)

在此处找到一个有效的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

它是在2.7中引入的,参见docs

如果需要输出,请使用subprocess.Popen

>>> import subprocess
>>> output = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0]

如果您希望运行的代码中大量使用了它,但不必长期维护该代码(或者您需要一个快速修复,而不管将来可能遇到的维护难题),那么您可以在导入子流程的任何地方隐藏punch(也称为monkey patch)。。。

把代码从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

可能需要轻微坐立不安。

请记住,尽管你有责任维护像这样肮脏的小后门。如果在最新的python中发现并更正了错误,那么您a)必须注意到这一点,b)如果您想保持安全,请更新您的版本。另外,亲自定义内部功能是下一个家伙最可怕的噩梦,尤其是当下一个家伙是几年前的你,而你已经忘记了你上一次做的那些恶心的黑客!总而言之:这很少是个好主意。

相关问题 更多 >