Skip to content Skip to sidebar Skip to footer

Interrupting Python Raw_input() In A Child Thread With ^c/keyboardinterrupt

In a multithreaded Python program, one thread sometimes asks for console input using the built-in raw_input(). I'd like to be able to be able to close the program while at a raw_in

Solution 1:

When join is called with no timeout, it is uninterruptable, but when it is called with a timeout, it is interruptable. Try adding an arbitrary timeout and putting it in a while loop:

while my_thread.isAlive():
    my_thread.join(5.0)

Solution 2:

There is really no easy way around this, period.

One approach is to reorganize and break up your code in a way that parts of functions which need Ctrl-C interruptibility are executed on the main thread. You use queues to send execution requests and likewise for the result values. You need one input queue for the main thread, and one output queue per non-main thread; and a coordinated main thread exit. Obviously, only one blocking function is executed at any given time this way, which may not be what you want.

Here's a working example of this idea with slightly perverse use of semaphores for the coordinated main thread exit.

Post a Comment for "Interrupting Python Raw_input() In A Child Thread With ^c/keyboardinterrupt"