我知道当你创建一个类newThread = MyThread(property)并且run()被触发时会自动调用__init __()newthread.start().我正在寻找的是在线程终止之前自动调用的东西,所以我不必self.cleanUp()在每个return语句之前显式调用.
class MyThread(Thread):
def __init__(self, property):
Thread.__init__(self)
self.property = property
def cleanUp(self):
# Clean up here
def run(self):
# Do some stuff
self.cleanUp() # Current work around
return
Run Code Online (Sandbox Code Playgroud)
一种方法是通过使Thread子类也成为上下文管理器.这将有效地使__exit__()您想要触发的特殊方法.
以下显示了我的建议.注意:我重命名了property您传递构造函数的参数,因为它property是Python内置的名称.
from threading import Thread
import time
TEST_THREAD_EXCEPTION = False # change as desired
class MyThread(Thread):
def __init__(self, attribute):
Thread.__init__(self)
self.attribute = attribute
def cleanup(self):
# Clean up here
print(' cleaning up after thread')
def run(self):
if TEST_THREAD_EXCEPTION:
raise RuntimeError('OOPS!') # force exception
print(' other thread now running...')
time.sleep(2) # Do something...
def __enter__(self):
try:
self.run()
except Exception as exc:
print('Error: {} exception raised by thread'.format(exc))
raise # reraise the exception
return self
def __exit__(self, *args):
self.cleanup()
print('main thread begins execution')
with MyThread('hello') as thread:
print('doing other things in main thread while other thread is running')
print('main thread continuing...')
Run Code Online (Sandbox Code Playgroud)
输出:
main thread begins execution
other thread now running...
doing other things in main thread while other thread is running
cleaning up after thread
main thread continuing on...
Run Code Online (Sandbox Code Playgroud)
如果更改TEST_THREAD_EXCEPTION为True,cleanup() 则不会被调用,因为线程未成功运行 - 尽管如果您愿意可以更改它,但可能还需要确保它不会被调用两次.以下是上述代码在这种情况下的作用:
main thread begins execution
Error: OOPS! exception raised by thread
Traceback (most recent call last):
File "opposite_init.py", line 37, in <module>
with MyThread('hello') as thread:
File "opposite_init.py", line 27, in __enter__
self.run()
File "opposite_init.py", line 21, in run
raise RuntimeError('OOPS!') # force exception
RuntimeError: OOPS!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2037 次 |
| 最近记录: |