Python 出现错误 - AttributeError: 'module' 对象在运行 subprocess.run(["ls", "-l"]) 时没有属性 'run'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40590192/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:42:15  来源:igfitidea点击:

Getting an error - AttributeError: 'module' object has no attribute 'run' while running subprocess.run(["ls", "-l"])

pythonpython-2.7subprocessaix

提问by nisarga lolage

I am running on a AIX 6.1 and using Python 2.7. Want to execute following line but getting an error.

我在 AIX 6.1 上运行并使用 Python 2.7。想要执行以下行但出现错误。

subprocess.run(["ls", "-l"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'run'

回答by Martijn Pieters

The subprocess.run()functiononly exists in Python 3.5 and newer.

subprocess.run()函数仅存在于 Python 3.5 及更新版本中。

It is easy enough to backport however:

然而,向后移植很容易:

def run(*popenargs, **kwargs):
    input = kwargs.pop("input", None)
    check = kwargs.pop("handle", False)

    if input is not None:
        if 'stdin' in kwargs:
            raise ValueError('stdin and input arguments may not both be used.')
        kwargs['stdin'] = subprocess.PIPE

    process = subprocess.Popen(*popenargs, **kwargs)
    try:
        stdout, stderr = process.communicate(input)
    except:
        process.kill()
        process.wait()
        raise
    retcode = process.poll()
    if check and retcode:
        raise subprocess.CalledProcessError(
            retcode, process.args, output=stdout, stderr=stderr)
    return retcode, stdout, stderr

There is no support for timeouts, and no custom class for completed process info, so I'm only returning the retcode, stdoutand stderrinformation. Otherwise it does the same thing as the original.

不支持超时,也没有用于完成进程信息的自定义类,所以我只返回retcode,stdoutstderr信息。否则它会做与原始相同的事情。