通过守护线程在文件中写入内容

Write something in a file by a Daemon Thread

我正在尝试通过守护线程在文件中写入内容。问题是文件正在创建,但它是空的。是否可以通过守护线程写入文件?

使用守护线程的原因是我的主程序比我的线程先终止。因此,为了保持该线程 运行 即使在使用程序守护程序执行后也是如此。

代码如下:

import threading

def hlp():
    with open("/path/to/y.txt",mode="w") as f:
        f.write("Hello")

def test():
    thr=threading.Thread(target=hlp)
    thr.daemon=True
    thr.start()

test()

Coming from here,当你使用守护线程时,看起来你需要 join 线程启动后:

换句话说:

with join - interpreter will wait until your process get completed or terminated, in this case file being written

import threading
def hlp():
    with open("C:\Users\munir.khan\PycharmProjects\opencv-basics2019-03-22_14-49-26\y.txt",mode="a+") as f:
        f.write("Hello")

def test():
    thr=threading.Thread(target=hlp)
    thr.daemon=True
    thr.start()
    thr.join()

test()

输出:

Hello

编辑:

如果你不想用join,你可以设置thr.daemon=False,但我不喜欢,因为这里说Setting thread.daemon = True allows the main program to exit.

import threading
def hlp():
    with open("C:\Users\munir.khan\PycharmProjects\opencv-basics2019-03-22_14-49-26\y.txt",mode="a+") as f:
        f.write("Hello")

def test():
    thr=threading.Thread(target=hlp)
    thr.daemon=False
    thr.start()

test()

使用守护线程可能不是您想要的,因为守护线程不会在程序退出之前等待线程完成。

如果您仍想使用守护进程,您应该使用 .join() 以便等待该线程完成。

示例:

import threading

def hlp():
    with open("/path/to/y.txt",mode="w") as f:
        f.write("Hello")

def test():
    thr=threading.Thread(target=hlp)
    thr.daemon=True
    thr.start()
    thr.join()

test()