我是 Python 新手。这是我的代码:
import logging
logging.basicConfig(level = logging.DEBUG, format = "[%(levelname)s] (%(threadName)-10s) %(message)s")
import threading
import time
def thread1():
for i in range(0, 10, 2):
logging.debug(i)
time.sleep(1)
def thread2():
for i in range(10, 20):
logging.debug(i)
time.sleep(1)
t1 = threading.Thread(name = "thread1", target = thread1)
t1.setDaemon(True)
t1.start()
t2 = threading.Thread(name = "thread2", target = thread2)
t2.setDaemon(True)
t2.start()
当我复制代码并将其粘贴到 python 命令行提示符时,我得到了以下结果。
如您所见,2 个线程已经完成,但程序似乎没有退出(我没有返回命令提示符)。我认为这与我的代码没有属性结束线程有关。真的吗?如何解决这个问题? 谢谢。
最佳答案
实际上,命令提示符在行 >>> [DEBUG] (thread1 ) 2
中返回,并准备好进行更多输入。守护线程在后台运行,打印它们应该打印的内容并最终完成。您根本不需要键入 ctrl-c。您可能刚刚输入了另一个 python 命令。
关于python - 如何正确停止 python 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19364688/