【发布时间】:2023-03-29 13:36:01
【问题描述】:
我想在用户按下 ctrl-C 时停止我的程序。
以下答案建议捕获KeyboardInterrupt 异常。
python: how to terminate a thread when main program ends
有时它会起作用。但在以下示例中,当我将线程数从 25 增加到 30 后,它停止工作。
import threading, sys, signal, os
stderr_lock = threading.Lock()
def Log(module, msg):
with stderr_lock:
sys.stderr.write("%s: %s\n" % (module, msg))
class My_Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
Log("Init", "Initing.")
self.start()
def run(self):
try:
while True:
Log("Run", "Running.")
except KeyboardInterrupt:
os._exit(0)
for i in range(30):
My_Thread()
# trap ctrl-C in main thread
try:
while True:
pass
except KeyboardInterrupt:
os._exit(0)
这与以下问题的感觉非常可疑:
Thread-Safe Signal API in Python 2.7
在那种情况下,我将线程数增加到超过 87 个后无法捕获信号。
【问题讨论】:
-
这对我来说很好。您使用的是什么操作系统?
-
不需要线程中的
KeyboardInterrupt -
@JohanL Ubuntu14。出于好奇,如果将范围(30)增加到范围(1000),它仍然有效吗?
-
在 1000 个线程时,我遇到了和你一样的问题。请参阅我对为什么以及您可以做些什么的回答。
标签: python multithreading python-2.7 keyboardinterrupt