通过守护线程在文件中写一些东西

时间:2019-03-26 06:45:46

标签: python python-multithreading

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

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

下面是代码:

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()

2 个答案:

答案 0 :(得分:2)

Coming from here,在与守护程序线程一起玩时,看起来好像需要在启动线程之后join

换句话说:

  

join-解释器将等待,直到您的过程完成或   终止,在这种情况下,文件被写入

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()

答案 1 :(得分:1)

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

如果仍然要使用守护程序,则应使用.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()

相关问题