【发布时间】:2019-09-25 19:00:41
【问题描述】:
我从https://www.bogotobogo.com/python/Multithread/python_multithreading_Daemon_join_method_threads.php 中获取了一段代码并添加了三行代码,期望它可以运行一个删除任何名为 'Tested' 的文件的守护进程。它在开始时工作,但如果在运行守护进程时(我猜它做到了),我使用“触摸测试”从命令行(在 GNU/linux 中)创建一个新文件,什么也没有发生。我读过它,但如果真的线程守护进程在后台工作,我应该做错了。
import threading
import time
import logging
import os
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-9s) %(message)s',)
def n():
logging.debug('Starting')
logging.debug('Exiting')
def d():
logging.debug('Starting')
# I expected these three following lines keep running in the background and delete any new file named 'Test'
while True:
if os.path.isfile('test'):
os.remove ('test')
time.sleep(5)
logging.debug('Exiting')
if __name__ == '__main__':
t = threading.Thread(name='non-daemon', target=n)
d = threading.Thread(name='daemon', target=d)
d.setDaemon(True)
d.start()
t.start()
【问题讨论】:
-
我猜主程序退出了。因为您没有将线程重新加入主线程..尝试将其重新加入主线程
-
但是加入等待所有加入的线程都完成了。我想要一个线程“永远”运行。我的问题是为什么里面的代码不起作用
-
你可以尝试将睡眠功能移到 while true 块下吗?
-
Yatish,我解决了问题:d.setDaemon(True) 不起作用。我用 d.setDaemon = True 替换这条指令,效果很好。谢谢
-
我也试过 d = threading.Thread(name='daemon', target=d, daemon = True) 但不起作用。
标签: python python-3.x python-multithreading python-daemon