如何退出一个运行线程的Python程序?

1 投票
1 回答
2660 浏览
提问于 2025-04-16 21:31

我正在写一些简单的代码,使用Pygame来处理图形,并且我有一个线程负责绘制所有内容。当我调用sys.exit()或者直接按ctrl+c时,主程序会退出,但那个线程似乎还在运行。我觉得我需要先把它关闭。该怎么做呢?

举个例子:

import threading

class Bla(threading.Thread):
    def run(self):
        print "I draw here"

Bla().start()

while True:
     if user_wants_to_end:
         sys.exit()

而且当我想退出程序时,程序却没有退出!我该怎么关闭这个线程呢?

1 个回答

2

Python程序会在所有非守护线程完成后退出。

class Bla(threading.Thread):
    daemon = True # Make the thread daemon
    def run(self):
        print "I draw here"

撰写回答