守护程序在Python的背景中

时间:2014-04-24 12:08:15

标签: python daemon

我需要像守护进程一样在后台运行这个脚本,直到现在我才能做到但不能在后台工作:

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

我已经尝试了另一种方法,但是在我看起来没有任何其他工作方式,还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

如果您希望将脚本作为守护程序运行,一种好的方法是使用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秒为文件追加一次。