Python 3 键盘中断多线程
Python 3 KeyboardInterrupt Multithreading
我试图让主线程等待其工作线程完成使用以下代码,但是当我尝试使用 Ctrl+C 中断它时它不会停止
import threading
import sys
exit = threading.Event()
#pass it to the threads
try:
exit.wait()
print('Goodbye')
sys.exit()
except KeyboardInterrupt:
print('Interrupted')
sys.exit()
更新
什么都不打印。所有后台线程都是守护进程。
import threading
import sys
import time
exit = threading.Event()
#pass it to the threads
try:
print("hi")
time.sleep(20)
print('Goodbye')
sys.exit()
except KeyboardInterrupt:
print('Interrupted')
sys.exit()
请尝试上面的语句来测试你的代码。我已经对其进行了测试,它对我来说工作正常。
当您使用 exit.wait() 时没有给出任何超时,它的 运行 无限秒。所以请花一些时间作为一个参数。
请遵循以下代码:
exit = threading.Event()
#pass it to the threads
try:
print("hi")
exit.wait(5)
print('Goodbye')
sys.exit()
except KeyboardInterrupt:
print('Interrupted')
sys.exit()
我试图让主线程等待其工作线程完成使用以下代码,但是当我尝试使用 Ctrl+C 中断它时它不会停止
import threading
import sys
exit = threading.Event()
#pass it to the threads
try:
exit.wait()
print('Goodbye')
sys.exit()
except KeyboardInterrupt:
print('Interrupted')
sys.exit()
更新 什么都不打印。所有后台线程都是守护进程。
import threading
import sys
import time
exit = threading.Event()
#pass it to the threads
try:
print("hi")
time.sleep(20)
print('Goodbye')
sys.exit()
except KeyboardInterrupt:
print('Interrupted')
sys.exit()
请尝试上面的语句来测试你的代码。我已经对其进行了测试,它对我来说工作正常。
当您使用 exit.wait() 时没有给出任何超时,它的 运行 无限秒。所以请花一些时间作为一个参数。 请遵循以下代码:
exit = threading.Event()
#pass it to the threads
try:
print("hi")
exit.wait(5)
print('Goodbye')
sys.exit()
except KeyboardInterrupt:
print('Interrupted')
sys.exit()