高效的Python守护程序 [英] Efficient Python Daemon

查看:98
本文介绍了高效的Python守护程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was curious how you can run a python script in the background, repeating a task every 60 seconds. I know you can put something in the background using &, is that effeictive for this case?

我当时正在考虑做一个循环,等待60秒钟并加载它

I was thinking of doing a loop, having it wait 60s and loading it again, but something feels off about that.

推荐答案

我认为您的想法几乎就是您想要的。例如:

I think your idea is pretty much exactly what you want. For example:

import time

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

def run():
    while True:
        time.sleep(60)
        do_something()

if __name__ == "__main__":
    run()

调用 time.sleep(60)将使您程序睡眠60秒。时间到了,操作系统将唤醒您的程序并运行 do_something()函数,然后使其重新进入睡眠状态。当程序处于睡眠状态时,它无法高效执行任何操作。这是编写后台服务的一般模式。

The call to time.sleep(60) will put your program to sleep for 60 seconds. When that time is up, the OS will wake up your program and run the do_something() function, then put it back to sleep. While your program is sleeping, it is doing nothing very efficiently. This is a general pattern for writing background services.

要从命令行实际运行,可以使用&:

To actually run this from the command line, you can use &:

$ python background_test.py &

执行此操作时,脚本的任何输出都将与启动该脚本的终端相同从。您可以重定向输出以避免这种情况:

When doing this, any output from the script will go to the same terminal as the one you started it from. You can redirect output to avoid this:

$ python background_test.py >stdout.txt 2>stderr.txt &

这篇关于高效的Python守护程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆