gpt4 book ai didi

python - 高效的 Python 守护进程

转载 作者:IT老高 更新时间:2023-10-28 22:01:21 24 4
gpt4 key购买 nike

我很好奇如何在后台运行 python 脚本,每 60 秒重复一次任务。我知道你可以使用 & 在后台添加一些东西,这对这种情况有效吗?

我正在考虑做一个循环,让它等待 60 秒并再次加载,但感觉有些不对劲。

最佳答案

与其编写自己的守护进程,不如使用 python-daemon反而! python-daemon实现 PEP 3143 的良好守护程序规范, “标准守护进程库”。

我已经包含了基于该问题的公认答案的示例代码,尽管代码看起来几乎相同,但它有一个重要的根本区别。没有 python-daemon您必须使用 & 将您的进程置于后台并使用 nohup 并防止您的进程在退出 shell 时被杀死。相反,它会在您运行程序时自动与您的终端分离。

例如:

import daemon
import time

def do_something():
while True:
with open("/tmp/current_time.txt", "w") as f:
f.write("The time is now " + time.ctime())
time.sleep(5)

def run():
with daemon.DaemonContext():
do_something()

if __name__ == "__main__":
run()

实际运行它:

python background_test.py

注意这里没有&

另外,this other stackoverflow answer详细解释使用 python-daemon 的诸多好处.

关于python - 高效的 Python 守护进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4637420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com