【问题标题】:Python: Unable to open and write to file from threadPython:无法从线程打开和写入文件
【发布时间】:2017-09-13 14:46:49
【问题描述】:

我正在尝试从线程创建/打开并写入文件。

from threading import Thread


CONNECTION_PORT = 9191

def testl():
    file = open("testfile.txt","w") 
    file.write("Hello World") 
    file.write("This is our new text file") 
    file.write("and this is another line.") 
    file.write("Why? Because we can.") 

    file.close() 

def test():
    t = Thread(target=testl)
    # t.daemon = True
    t.start()


test() 

问题是,当我取消注释测试函数的第二行 (t.daemon = True) 时,它停止工作。有没有办法让它在守护线程模式下工作??

我在互联网上找不到任何解决方案,甚至找不到与此相关的解决方案。我知道这不是文件操作的最佳方式。

【问题讨论】:

标签: python multithreading


【解决方案1】:

守护线程意味着python在程序退出之前不需要等待线程完成。 那么,会发生什么:

  • test() 启动线程

  • test()结束,包含test()的线程(可能是主线程)结束

  • 没有非守护线程

  • python 退出。

我真的不认为您希望线程成为守护线程。 如果你这样做了,你应该有一些非守护线程调用t.join(),这样你就可以等待那个线程完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多