Triggering an exception in a main thread from a daemon thread in Python

余生颓废 提交于 2019-12-12 05:11:12

问题


How do you trigger an exception in a main thread, running blocking code, from a daemon thread in Python?

I have a daemon thread that periodically checks a database for a record indicating that its current process should terminate (i.e. the user has pressed the "cancel" button). In my main non-daemon thread, I'm running a blocking call to an external process that I can't easily modify to gracefully terminate. However, the main thread can gracefully handle a normal KeyboardInterrupt when I manually trigger one.

So if my daemon thread receives the terminate command, how do I raise an exception in my main thread to terminate my process?


回答1:


After digging through the thread docs, I finally found the solution to be interrupt_main().




回答2:


You can get your subprocess returncode with the returncode attribute. Raise something if it's different from zero.

Edit: I've mixed up the subprocess and multiprocessing modules. There is however an exitcode attribute in the multiprocessing module that seems similar to the subprocess returncode attribute.




回答3:


It's typically done using a message queue. See Catch a thread's exception in the caller thread in Python

However it will not preempt your main thread, you will have to actively poll for it. Maybe with signals you'll be able to get what you need.



来源:https://stackoverflow.com/questions/10605538/triggering-an-exception-in-a-main-thread-from-a-daemon-thread-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!