高效的 Python 守护进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4637420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:41:13  来源:igfitidea点击:

Efficient Python Daemon

pythondaemon

提问by Kyle Hotchkiss

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?

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

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

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

采纳答案by Greg Hewgill

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

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.

调用time.sleep(60)将使您的程序休眠 60 秒。当该时间结束时,操作系统将唤醒您的程序并运行该do_something()功能,然后将其重新置于睡眠状态。当您的程序处于休眠状态时,它不会非常有效地执行任何操作。这是编写后台服务的通用模式。

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 &

回答by Kevin Dolan

Using & in the shell is probably the dead simplest way as Greg described.

正如 Greg 所描述的那样,在 shell 中使用 & 可能是最简单的方法。

If you really want to create a powerful Daemon though, you will need to look into the os.fork() command.

如果你真的想创建一个强大的守护进程,你需要查看 os.fork() 命令。

The example from Wikipedia:

来自维基百科的例子:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, time

def createDaemon():
  """ 
      This function create a service/Daemon that will execute a det. task
  """

  try:
    # Store the Fork PID
    pid = os.fork()

    if pid > 0:
      print 'PID: %d' % pid
      os._exit(0)

  except OSError, error:
    print 'Unable to fork. Error: %d (%s)' % (error.errno, error.strerror)
    os._exit(1)

  doTask()

def doTask():
  """ 
      This function create a task that will be a daemon
  """

  # Open the file in write mode
  file = open('/tmp/tarefa.log', 'w')

  # Start the write
  while True:
    print >> file, time.ctime()
    file.flush()
    time.sleep(2)

  # Close the file
  file.close()

if __name__ == '__main__':

  # Create the Daemon
  createDaemon()

And then you could put whatever task you needed inside the doTask()block.

然后你可以把你需要的任何任务放在doTask()块中。

You wouldn't need to launch this using &, and it would allow you to customize the execution a little further.

您不需要使用 & 启动它,它允许您进一步自定义执行。

回答by aculich

Rather than writing your own daemon, use python-daemoninstead! python-daemonimplements the well-behaved daemon specification of PEP 3143, "Standard daemon process library".

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

I have included example code based on the accepted answer to this question, and even though the code looks almost identical, it has an important fundamental difference. Without python-daemonyou would have to use &to put your process in the background and nohupand to keep your process from getting killed when you exit your shell. Instead this will automatically detach from your terminal when you run the program.

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

For example:

例如:

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

To actually run it:

要实际运行它:

python background_test.py

And note the absence of &here.

并注意&这里的缺席。

Also, this other stackoverflow answerexplains in detail the many benefits of using python-daemon.

此外,this other stackoverflow answer详细解释了使用python-daemon的许多好处。