2012-08-30 18 views
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' 

有什么办法与关键字的保证清理代码结合执行一个线程类?

+0

你的意思是f.run()? – squiguy

回答

-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() 
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构造中变量的原因。

作为suggested by @linjunhalida的线程加入__exit__也是一个好主意,但不会导致您目前的问题。

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