我需要像守护进程一样在后台运行这个脚本,到目前为止我只能让它工作,但不能在后台运行:
import threading
from time import gmtime, strftime
import time
def write_it():
#this function write the actual time every 2 seconds in a file
threading.Timer(2.0, write_it).start()
f = open("file.txt", "a")
hora = strftime("%Y-%m-%d %H:%M:%S", gmtime())
#print hora
f.write(hora+"\n")
f.close()
def non_daemon():
time.sleep(5)
#print 'Test non-daemon'
write_it()
t = threading.Thread(name='non-daemon', target=non_daemon)
t.start()
我已经尝试过其他方法,但它们都没有在我寻找的后台工作,还有其他选择吗?
最佳答案
如果您希望将脚本作为守护进程运行,一种好的方法是使用 Python Daemon图书馆。下面的代码应该可以实现您想要实现的目标:
import daemon
import time
def write_time_to_file():
with open("file.txt", "a") as f:
hora = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
f.write(hora+"\n")
with daemon.DaemonContext():
while(True):
write_time_to_file()
time.sleep(2)
在本地进行了测试,效果很好,每 2 秒向文件添加一次时间。
关于python - python 后台守护进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23268464/