“ctrl+c”不能在windows上使用此python代码

2024-10-01 09:38:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的mac中,ctrl + c与此python代码配合得非常好。因此,脚本退出时出现KeyboardInterrupt异常

但是在Windows10中,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()


我使用conda,python3.9.7在{}中运行这段代码

我认为“线程中的线程”会产生问题,但问题似乎就在线程中

对不起,这个问题只在我的环境中出现


Tags: 代码importtruetimemaindefsleepthread
2条回答

问题可能是,当您尝试在线程上使用键盘中断时,线程被挂起。尝试在生成新线程的地方捕获KeyboardInterruptexception,并在那里加入它们

这里发生了几件事

https://docs.python.org/3/library/signal.html#signals-and-threads

Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread.

主线程创建一个非守护进程线程,并使用无限循环运行test_func()。然后主线程退出。非守护进程线程继续打印消息,然后休眠3秒钟,以此类推

由于中断处理程序位于主线程上,因此非守护进程线程将保持运行,按Ctrl+C不会停止执行

但是,在Windows上,当Ctrl+C不起作用时,通常可以按Ctrl+PauseCtrl+ScrLk来终止Python进程

如果代码运行test_func(),并在主键盘上执行sleep调用,则按Ctrl+C将引发键盘中断异常

def main():
    test_func()
    # thread0 = threading.Thread(target=test_func)
    # thread0.daemon = True
    # thread0.start()

相关问题 更多 >