获取错误 - AttributeError:'module'对象在运行subprocess.run时没有属性'run'([“ls”,“ - l”])

问题描述 投票:13回答:1

我在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'
python python-2.7 subprocess aix
1个回答
23
投票

subprocess.run() function仅存在于Python 3.5及更高版本中。

然而,向后移动很容易:

def run(*popenargs, input=None, check=False, **kwargs):
    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

不支持超时,也没有完成流程信息的自定义类,因此我只返回retcodestdoutstderr信息。否则它与原始版本完全相同。

© www.soinside.com 2019 - 2024. All rights reserved.