在我的mac中,ctrl + c
与这个python代码一起工作得很好。所以脚本退出KeyboardInterrupt异常。
但是在windows 10中,ctrl + c
根本不起作用。所以脚本永远运行。
我不知道是什么问题。
下面是我的代码:import time
import threading
def fast_scrap():
pass
def slow_scrap_thread(keyword_list: list):
sleep_time = 2
for keyword in keyword_list:
print(keyword)
print("sleep " + str(sleep_time) + "secs")
time.sleep(sleep_time)
def slow_scrap():
rounds = 0
while True:
keyword_list = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']
keyword_lists = list()
threads = list()
for i in range(len(keyword_list) // 3 + 1):
keyword_lists.append(keyword_list[i * 3:i * 3 + 3])
for keyword_list in keyword_lists:
thread = threading.Thread(target=slow_scrap_thread, args=(keyword_list, ))
# thread.daemon = True
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print("rounds: " + str(rounds))
time.sleep(3)
rounds += 1
def main():
thread0 = threading.Thread(target=fast_scrap)
# thread0.daemon = True
thread0.start()
thread1 = threading.Thread(target=slow_scrap)
# thread1.daemon = True
thread1.start()
if __name__ == "__main__":
main()
我认为我的代码中线程有问题,但不确定是什么问题。
-------------------- 编辑 ---------------------
对不起,这里有更多的最小代码:
import time
import threading
def test_func():
rounds = 0
while True:
print("test_func")
print("rounds: " + str(rounds))
time.sleep(3)
rounds += 1
def main():
thread0 = threading.Thread(target=test_func)
# thread0.daemon = True
thread0.start()
if __name__ == "__main__":
main()
和我运行这段代码在cmd
使用conda, python 3.9.7
我认为"线程中线程"会产生问题,但问题似乎只是在线程中。
对不起,这个问题只是在我的环境??
这里有几件事。
从https://docs.python.org/3/library/signal.html # signals-and-threads:
Python信号处理程序总是在主解释器的Python主线程中执行,即使信号是在另一个线程中接收到的。
主线程创建一个非守护线程,并运行test_func()无限循环。然后主线程退出。非守护线程继续打印msg,然后休眠3秒,以此类推,直到永远。
由于中断处理程序在主线程上,非守护线程继续运行,按Ctrl+C对停止执行没有影响。
然而,在Windows上,当Ctrl+C不起作用时,通常可以按Ctrl+Pause或Ctrl+ScrLk来终止Python进程。
如果代码运行test_func()并在主标题上调用sleep,那么按Ctrl+C将引发KeyboardInterrupt异常。
def main():
test_func()
# thread0 = threading.Thread(target=test_func)
# thread0.daemon = True
# thread0.start()
问题可能是当您尝试在线程上使用键盘中断时,线程被挂起。尝试在生成新线程的地方捕获KeyboardInterrupt
异常,并在那里加入它们。