首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取错误-模块:运行subprocess.run(["ls","-l"])时,‘AttributeError’对象没有'run‘属性

获取错误-模块:运行subprocess.run(["ls","-l"])时,‘AttributeError’对象没有'run‘属性
EN

Stack Overflow用户
提问于 2016-11-14 21:44:59
回答 2查看 71.8K关注 0票数 35

我在AIX6.1上运行,使用的是Python2.7。我想执行下面的代码行,但是得到了一个错误。

代码语言:javascript
运行
复制
subprocess.run(["ls", "-l"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'run'
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-11-14 21:57:43

subprocess.run() function只存在于Python3.5和更新版本中。

然而,向后移植很容易:

代码语言:javascript
运行
复制
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信息。否则,它会做与原始文件相同的事情。

票数 52
EN

Stack Overflow用户

发布于 2021-03-04 04:50:06

公认的答案是不起作用的代码,并且也没有与原始(Python 3)函数相同的返回。然而,它足够相似,它不是CC BY 4.0martjn Pieters,因为它是从Python复制的,如果有任何许可证应用于琐碎的代码(我完全反对琐碎代码的许可,因为它阻碍了创新和证明所有权或原创性是困难的,所以stackoverflow很可能违反了包括通用公共许可证在内的各种许可证,通过重新许可人们粘贴并默认声称为自己的东西而没有引用来源的额外限制),这将在下面的GitHub链接。如果代码不能以同样的方式使用,那么它就不是“后向移植”。如果您尝试以Python3的方式使用它而不更改您的代码(使用函数的客户端代码),您将只会得到"AttributeError:'tuple‘object has no attribute 'returncode'“。您可以更改您的代码,但它将与Python3不兼容。

无论哪种方式,接受答案本身中的代码都不会运行,因为:

  1. "TypeError:init()获取了意外的关键字参数' stderr '“(因为在2或3中,stderr不是"CalledProcessError”的参数)

  1. "AttributeError:'Popen‘对象没有属性'args'“(args仅在Python3中可用)

因此,请考虑更改接受的答案。

为了更具Python化的特点,我们利用了鸭子类型和猴子补丁(您的客户端代码可以保持不变,并为run方法和返回的对象的类使用如下所示的不同定义),下面是一个与Python 3兼容的实现:

代码语言:javascript
运行
复制
import subprocess
try:
    from subprocess import CompletedProcess
except ImportError:
    # Python 2


    class CompletedProcess:

        def __init__(self, args, returncode, stdout=None, stderr=None):
            self.args = args
            self.returncode = returncode
            self.stdout = stdout
            self.stderr = stderr

        def check_returncode(self):
            if self.returncode != 0:
                err = subprocess.CalledProcessError(self.returncode, self.args, output=self.stdout)
                raise err
            return self.returncode

    def sp_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:
            outs, errs = process.communicate(input)
        except:
            process.kill()
            process.wait()
            raise
        returncode = process.poll()
        if check and returncode:
            raise subprocess.CalledProcessError(returncode, popenargs, output=outs)
        return CompletedProcess(popenargs, returncode, stdout=outs, stderr=errs)

    subprocess.run = sp_run
    # ^ This monkey patch allows it work on Python 2 or 3 the same way

这段代码已经在我的install_any.py (参见https://github.com/poikilos/linux-preinstall/tree/master/utilities)中使用在Python2和Python3中工作的测试用例进行了测试。

注意:这个类没有相同的Python 字符串,并且可能有其他细微的差异(您可以使用Python3本身的真实代码,根据它的许可--请参阅https://github.com/python/cpython/blob/master/Lib/subprocess.py中的类CalledProcess --该许可也适用于我的代码,如果有的话,但我将其作为CC0发布,因为我认为它微不足道--请参阅上面括号中的解释)。

#IRejectTheInvalidAutomaticLicenseForMyPost

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40590192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档