python后台守护进程

python后台守护进程,python,daemon,Python,Daemon,我需要像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("

我需要像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()

我已经尝试过其他方法,但没有一种方法可以在后台工作,正如我所看到的,还有其他方法吗?

如果您希望将脚本作为守护进程运行,一个好方法是使用该库。下面的代码应该实现您希望实现的目标:

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秒向文件追加一次时间。

在这种情况下,守护进程意味着什么?您是否需要在后台运行应用程序作为自己的进程,还是希望
write_it()
在应用程序执行其他操作时“在后台”运行?其想法是将write_it()后台化并能够执行其他操作问题到底是什么?该线程在后台运行,您可以继续运行代码。使用当前代码,write_it()作为“守护进程”在后台运行-您希望能够运行其他/python/代码还是希望程序停止(如在python进程分叉中)?我只想让此代码运行,同时我可以做一些事情,我试过了,它在后台运行,但它没有附加任何东西:/您只是运行我自己编写的代码(在python shell中对我起作用)还是将其包装到其他东西中执行?