python 中的守护线程与非守护线程

Daemon thread vs Non Daemon thread in python

我有以下代码:

import threading 
from time import sleep

def print_function1():
    while True:
        print("Hi this is function 1\n") 
        sleep(2)

if __name__ == "__main__": 
    # creating thread 
    t1 = threading.Thread(target=print_function1 ) 

    t1.daemon = True

    # starting thread 1 
    t1.start() 

    sleep(10)

    # both threads completely executed 
    print("Done!") 

现在我无法理解如果我设置 t1.daemon True 或 False 会有什么不同,我是 运行 蜘蛛代码 Ipython 控制台中的代码。

在这两种情况下,程序似乎都没有退出,它一直在打印 "Hi this is function 1"。 我的假设是守护线程将在主线程完成时保持 运行,但普通线程将退出。

谁能解释一下。

这个问题是因为在 运行 python 编码到 python shell 时观察到守护线程的不同行为,假设在我的 Spyder 中 Ipython case vs 运行 python 来自命令行的文件,如“python thread_example.py”。

运行 命令行中的文件给出了预期的行为。

可以参考这个 Whosebug 答案:Python daemon thread does not exit when parent thread exits

它使线程在后台 运行 不中断主要工作,而 true 或 运行 作为主线程,而 false