Python program with thread can't catch CTRL+C

后端 未结 2 1226
刺人心
刺人心 2020-12-17 22:40

I am writing a python script that needs to run a thread which listens to a network socket.

I\'m having trouble with killing it using Ctrl+c usi

2条回答
  •  悲哀的现实
    2020-12-17 23:04

    The issue is that after the execution falls off the main thread (after main() returned), the threading module will pause, waiting for the other threads to finish, using locks; and locks cannot be interrupted with signals. This is the case in Python 2.x at least.

    One easy fix is to avoid falling off the main thread, by adding an infinite loop that calls some function that sleeps until some action is available, like select.select(). If you don't need the main thread to do anything at all, use signal.pause(). Example:

    if __name__ == '__main__':
        signal.signal(signal.SIGINT, handler)
        main()
        while True:           # added
            signal.pause()    # added
    

提交回复
热议问题