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

发布于 2021-01-29 14:59:01

我在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'
关注者
0
被浏览
72
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    但是,向后移植很容易:

    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
    

    没有为超时的支持,并为完成过程信息没有自定义类,所以我只能返回retcodestdoutstderr信息。否则,它会执行与原始文件相同的操作。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看