如何从Python线程退出整个应用程序? [英] How to exit the entire application from a Python thread?
问题描述
如何从其线程之一退出整个Python应用程序? sys.exit()仅终止调用它的线程,因此无济于事.
How can I exit my entire Python application from one of its threads? sys.exit() only terminates the thread in which it is called, so that is no help.
我不想使用os.kill()解决方案,因为它不是很干净.
I would not like to use an os.kill() solution, as this isn't very clean.
推荐答案
If all your threads except the main ones are daemons, the best approach is generally thread.interrupt_main() -- any thread can use it to raise a KeyboardInterrupt
in the main thread, which can normally lead to reasonably clean exit from the main thread (including finalizers in the main thread getting called, etc).
当然,如果这导致某些非守护进程线程使整个过程保持活动状态,则您需要按照Mark的建议继续使用os._exit
,但是我认为这是最后的手段(有点像kill -9
;-),因为它相当残酷地终止了事情(终结器未运行,包括try/finally
块,with
块,atexit
函数等).
Of course, if this results in some non-daemon thread keeping the whole process alive, you need to followup with os._exit
as Mark recommends -- but I'd see that as the last resort (kind of like a kill -9
;-) because it terminates things quite brusquely (finalizers not run, including try/finally
blocks, with
blocks, atexit
functions, etc).
这篇关于如何从Python线程退出整个应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!