当我运行以下程序时:
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关键字的保证清理代码执行与线程类结合起来?
答案 0 :(得分: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__
作为suggested by @linjunhalida也是一个好主意,但不会导致您当前的问题。
如果您希望run
可以使用,还应将def run(self)
的定义更改为{{1}}。 :)
答案 1 :(得分:-3)
只需使用join 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()