python - python 后台守护进程

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

我已经尝试过其他方法,但它们都没有在我寻找的后台工作,还有其他选择吗?

最佳答案

如果您希望将脚本作为守护进程运行,一种好的方法是使用 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/

相关文章:

python - 如何配置 .condarc 以便默认在当前目录中创建新环境

Python - 如何使用 NetSuite Web 服务设置自定义字段

python - 统计目录和子目录中文件夹的数量

service - 如何在 Android TV Oreo 中始终运行服务/守护进程?

c - 在 C 中停止和启动 Unix 守护进程

c++ - 为什么我应该使用 fork() 来守护进程?

python - 如何在 python-vlc 中播放音乐时更改音量?

Python 一行获取枚举类列表的所有值的组合列表

Linux 守护进程 : alternative to chdir ("/")?

监视文件夹和更新数据库的 Python 守护进程