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

陌路散爱 提交于 2019-12-01 17:07:34

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)

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.

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