如何使 Python 脚本像 Linux 中的服务或守护程序一样运行

新手上路,请多包涵

我编写了一个 Python 脚本来检查某个电子邮件地址并将新电子邮件传递给外部程序。我怎样才能让这个脚本 247 执行,例如在 Linux 中把它变成守护进程或服务。我是否还需要一个永远不会在程序中结束的循环,还是可以通过多次重新执行代码来完成?

原文由 adhanlon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 396
2 个回答

您在这里有两个选择。

  1. 进行适当的 cron 作业 来调用您的脚本。 Cron 是 GNU/Linux 守护程序的通用名称,它根据您设置的计划定期启动脚本。您将脚本添加到 crontab 中或将符号链接放置到特殊目录中,守护程序会处理在后台启动它的工作。您可以在 Wikipedia 上 阅读更多 内容。有多种不同的 cron 守护程序,但您的 GNU/Linux 系统应该已经安装了它。

  2. 使用某种 python 方法(例如库)让您的脚本能够自行守护进程。是的,它需要一个简单的事件循环(您的事件是计时器触发,可能由睡眠功能提供)。

我不建议您选择 2.,因为实际上您会重复 cron 功能。 Linux 系统范式是让多个简单的工具交互并解决您的问题。除非有其他原因需要您制作守护程序(除了定期触发),否则请选择其他方法。

此外,如果您将 daemonize 与循环一起使用并且发生崩溃,则此后没有人会检查邮件(正如 Ivan Nevostruev对此 答案的评论中指出的那样)。而如果脚本作为 cron 作业添加,它将再次触发。

原文由 P Shved 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是从 这里 获取的一个不错的课程:

 #!/usr/bin/env python

import sys, os, time, atexit
from signal import SIGTERM

class Daemon:
        """
        A generic daemon class.

        Usage: subclass the Daemon class and override the run() method
        """
        def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
                self.stdin = stdin
                self.stdout = stdout
                self.stderr = stderr
                self.pidfile = pidfile

        def daemonize(self):
                """
                do the UNIX double-fork magic, see Stevens' "Advanced
                Programming in the UNIX Environment" for details (ISBN 0201563177)
                http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
                """
                try:
                        pid = os.fork()
                        if pid > 0:
                                # exit first parent
                                sys.exit(0)
                except OSError, e:
                        sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
                        sys.exit(1)

                # decouple from parent environment
                os.chdir("/")
                os.setsid()
                os.umask(0)

                # do second fork
                try:
                        pid = os.fork()
                        if pid > 0:
                                # exit from second parent
                                sys.exit(0)
                except OSError, e:
                        sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
                        sys.exit(1)

                # redirect standard file descriptors
                sys.stdout.flush()
                sys.stderr.flush()
                si = file(self.stdin, 'r')
                so = file(self.stdout, 'a+')
                se = file(self.stderr, 'a+', 0)
                os.dup2(si.fileno(), sys.stdin.fileno())
                os.dup2(so.fileno(), sys.stdout.fileno())
                os.dup2(se.fileno(), sys.stderr.fileno())

                # write pidfile
                atexit.register(self.delpid)
                pid = str(os.getpid())
                file(self.pidfile,'w+').write("%s\n" % pid)

        def delpid(self):
                os.remove(self.pidfile)

        def start(self):
                """
                Start the daemon
                """
                # Check for a pidfile to see if the daemon already runs
                try:
                        pf = file(self.pidfile,'r')
                        pid = int(pf.read().strip())
                        pf.close()
                except IOError:
                        pid = None

                if pid:
                        message = "pidfile %s already exist. Daemon already running?\n"
                        sys.stderr.write(message % self.pidfile)
                        sys.exit(1)

                # Start the daemon
                self.daemonize()
                self.run()

        def stop(self):
                """
                Stop the daemon
                """
                # Get the pid from the pidfile
                try:
                        pf = file(self.pidfile,'r')
                        pid = int(pf.read().strip())
                        pf.close()
                except IOError:
                        pid = None

                if not pid:
                        message = "pidfile %s does not exist. Daemon not running?\n"
                        sys.stderr.write(message % self.pidfile)
                        return # not an error in a restart

                # Try killing the daemon process
                try:
                        while 1:
                                os.kill(pid, SIGTERM)
                                time.sleep(0.1)
                except OSError, err:
                        err = str(err)
                        if err.find("No such process") > 0:
                                if os.path.exists(self.pidfile):
                                        os.remove(self.pidfile)
                        else:
                                print str(err)
                                sys.exit(1)

        def restart(self):
                """
                Restart the daemon
                """
                self.stop()
                self.start()

        def run(self):
                """
                You should override this method when you subclass Daemon. It will be called after the process has been
                daemonized by start() or restart().
                """

原文由 the_drow 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题