Python 脚本需要多次 CTRL + C 才能停止
Python script required multiple CTRL + C to stop
我有一个场景,我想处理 SIGINT int python 来清理一些东西然后退出。
我正在使用以下代码。
import threading
import signal
def shutdown_handler(*args):
raise SystemExit('Exiting')
signal.signal(signal.SIGINT, shutdown_handler)
def main():
while 1:
time.sleep(2)
print("***")
sub_thread = threading.Thread(target=main)
sub_thread.start()
sub_thread.join()
但是它要求我在程序退出前多次按下 CTRL + c。
以下工作正常
import time
import threading
import signal
def shutdown_handler(*args):
# Do some clean up here.
raise SystemExit('Exiting')
signal.signal(signal.SIGINT, shutdown_handler)
def main():
while 1:
time.sleep(2)
print("***")
main()
我正在使用第一个代码,因为 this 线程
上的建议
你能告诉我为什么会出现这种行为吗?是因为多个线程 运行 吗?我该如何解决这个问题?
谢谢
如果用 Control-C
终止程序是您唯一的要求,请在构造函数中设置 daemon=True
。
import threading
import signal
def shutdown_handler(*args):
raise SystemExit('Exiting')
signal.signal(signal.SIGINT, shutdown_handler)
def main():
while 1:
time.sleep(2)
print("***")
sub_thread = threading.Thread(target=main, daemon=True) # here
sub_thread.start()
sub_thread.join()
我有一个场景,我想处理 SIGINT int python 来清理一些东西然后退出。 我正在使用以下代码。
import threading
import signal
def shutdown_handler(*args):
raise SystemExit('Exiting')
signal.signal(signal.SIGINT, shutdown_handler)
def main():
while 1:
time.sleep(2)
print("***")
sub_thread = threading.Thread(target=main)
sub_thread.start()
sub_thread.join()
但是它要求我在程序退出前多次按下 CTRL + c。 以下工作正常
import time
import threading
import signal
def shutdown_handler(*args):
# Do some clean up here.
raise SystemExit('Exiting')
signal.signal(signal.SIGINT, shutdown_handler)
def main():
while 1:
time.sleep(2)
print("***")
main()
我正在使用第一个代码,因为 this 线程
上的建议
你能告诉我为什么会出现这种行为吗?是因为多个线程 运行 吗?我该如何解决这个问题?
谢谢
如果用 Control-C
终止程序是您唯一的要求,请在构造函数中设置 daemon=True
。
import threading
import signal
def shutdown_handler(*args):
raise SystemExit('Exiting')
signal.signal(signal.SIGINT, shutdown_handler)
def main():
while 1:
time.sleep(2)
print("***")
sub_thread = threading.Thread(target=main, daemon=True) # here
sub_thread.start()
sub_thread.join()