1

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?

Cerin
  • 60,957
  • 96
  • 316
  • 522

3 Answers3

1

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

Cerin
  • 60,957
  • 96
  • 316
  • 522
  • The link should read : https://docs.python.org/3/library/_thread.html It is the rare solution to stopping Django from code. – user508402 Jan 02 '17 at 16:17
0

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.

Arthur
  • 1,974
  • 2
  • 21
  • 28
0

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.

Community
  • 1
  • 1
sherve
  • 300
  • 2
  • 10