0

当我运行以下程序时:

import threading
class foo(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def __enter__(self):
        print "Enter"
    def __exit__(self, type, value, traceback):
        print "Exit"

    def run():
        print "run"



if __name__ == "__main__":
    with foo() as f:
        f.start()

我得到这个作为输出

C:\>python test2.py
Enter
Exit
Traceback (most recent call last):
  File "test2.py", line 17, in <module>
    f.start()
AttributeError: 'NoneType' object has no attribute 'start'

有没有办法将 with 关键字的保证清理代码执行与线程类结合起来?

4

2 回答 2

4
import threading
class foo(threading.Thread):
    def __enter__(self):
        print "Enter"
        return self
    def __exit__(self, type, value, traceback):
        self.join() # wait for thread finished
        print "Exit"
    def run(self):
        print "run"

if __name__ == "__main__":
    with foo() as f:
        f.start()

你的__enter__方法应该return self; 这就是分配给with ... as f构造中的变量的内容。

__exit__按照@linjunhalida 的建议让线程加入也是一个好主意,但不会导致您当前的问题。

如果您希望它可用,还应该更改runto的定义。def run(self):)

于 2012-08-30T01:20:14.540 回答
-3

只需使用连接等待线程完成执行:http: //docs.python.org/library/threading.html#threading.Thread.join

import threading
class foo(threading.Thread):
    def __init__(self):
        self.thread = threading.Thread.__init__(self)
    def __enter__(self):
        print "Enter"
    def __exit__(self, type, value, traceback):
        self.thread.join() # wait for thread finished
        print "Exit"

    def run():
        print "run"



if __name__ == "__main__":
    with foo() as f:
        f.start()
于 2012-08-30T01:19:22.280 回答