猿问

Python,AttributeError:RunCmd实例没有用于增量调试的属性“ p”

我有一个Python程序会产生错误:


File "myTest.py", line 34, in run

   self.output = self.p.stdout

AttributeError: RunCmd instance has no attribute 'p'

Python代码:


class RunCmd():


    def __init__(self, cmd):

        self.cmd = cmd


    def run(self, timeout):

        def target():

            self.p = sp.Popen(self.cmd[0], self.cmd[1], stdin=sp.PIPE,

                              stdout=sp.PIPE, stderr=sp.STDOUT)


        thread = threading.Thread(target=target)

        thread.start()

        thread.join(timeout)


        if thread.is_alive():

            print "process timed out"

            self.p.stdin.write("process timed out")

            self.p.terminate()

            thread.join()


        self.output = self.p.stdout             #self.p.stdout.read()?

        self.status = self.p.returncode


    def getOutput(self):

        return self.output


    def getStatus(self):

        return self.status

这是整个回溯轨迹。


Exception in thread Thread-1:

Traceback (most recent call last):

File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner

    self.run()

File "/usr/lib/python2.7/threading.py", line 505, in run

    self.__target(*self.__args, **self.__kwargs)

File "myTest.py", line 18, in target

    self.p = sp.Popen(self.cmd, stdin=PIPE,

NameError: global name 'PIPE' is not defined


Traceback (most recent call last):

File "myTest.py", line 98, in <module>

    c = mydd.ddmin(deltas)              # Invoke DDMIN

File "/home/DD.py", line 713, in ddmin

    return self.ddgen(c, 1, 0)

File "/home/DD.py", line 605, in ddgen

    outcome = self._dd(c, n)

File "/home/DD.py", line 615, in _dd

    assert self.test([]) == self.PASS

File "/home/DD.py", line 311, in test

    outcome = self._test(c)

File "DD.py", line 59, in _test

    test.run(3)

File "DD.py", line 30, in run

    self.status = self.p.returncode

AttributeError: 'RunCmd' object has no attribute 'p'

该错误是什么意思,它试图告诉我什么?


吃鸡游戏
浏览 256回答 2
2回答

慕妹3242003

您没有提供所有错误消息。线程中的代码失败,因为您对Popen的调用错误,应该是:def target():&nbsp; &nbsp; self.p = sp.Popen(self.cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.STDOUT)当线程失败时,它不会设置“ p”变量,这就是为什么您要获取正在谈论的错误消息的原因。

蝴蝶不菲

如何非常简单地在Python中重现此错误:class RunCmd():&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; print(self.p)r = RunCmd()印刷:AttributeError: 'RunCmd' object has no attribute 'p'这是怎么回事:您必须学习阅读和理解要处理的代码。像这样说出代码:我定义了一个名为RunCmd的类。它有一个__init__不带参数的构造函数。构造函数打印出局部成员变量p。我实例化了RunCmd类的新对象(实例)。运行构造函数,并尝试访问p的值。不存在这样的属性p,因此将打印错误消息。错误消息的含义与所讲的完全相同。您需要先创建一些东西,然后才能使用它。如果不这样做,将抛出此AttributeError。解决方案:早在未创建变量时抛出错误。将代码放入try / catch中,以在未创建程序时停止该程序。在使用变量之前,先测试该变量是否存在。
随时随地看视频慕课网APP

相关分类

Python
我要回答