Interrupting Python raw_input() in a child thread with ^C/KeyboardInterrupt

前端 未结 2 1454
遥遥无期
遥遥无期 2021-01-18 01:17

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

相关标签:
2条回答
  • 2021-01-18 01:28

    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)
    
    0 讨论(0)
  • 2021-01-18 01:34

    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.

    0 讨论(0)
提交回复
热议问题