简体   繁体   English

Python脚本作为linux服务/守护进程

[英]Python script as linux service/daemon

Hallo, 你好,

I'm trying to let a python script run as service (daemon) on (ubuntu) linux. 我想让一个python脚本在(ubuntu)linux上作为服务(守护进程)运行。

On the web there exist several solutions like: 在网上有几个解决方案,如:

http://pypi.python.org/pypi/python-daemon/ http://pypi.python.org/pypi/python-daemon/

A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. 一个表现良好的Unix守护进程很难做到,但每个守护进程程序所需的步骤大致相同。 A DaemonContext instance holds the behaviour and configured process environment for the program; DaemonContext实例保存程序的行为和配置的进程环境; use the instance as a context manager to enter a daemon state. 使用实例作为上下文管理器来进入守护程序状态。

http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/

However as I want to integrate my python script specifically with ubuntu linux my solution is a combination with an init.d script 但是,由于我想将我的python脚本专门与ubuntu linux集成,我的解决方案是与init.d脚本的组合

#!/bin/bash

WORK_DIR="/var/lib/foo"
DAEMON="/usr/bin/python"
ARGS="/opt/foo/linux_service.py"
PIDFILE="/var/run/foo.pid"
USER="foo"

case "$1" in
  start)
    echo "Starting server"
    mkdir -p "$WORK_DIR"
    /sbin/start-stop-daemon --start --pidfile $PIDFILE \
        --user $USER --group $USER \
        -b --make-pidfile \
        --chuid $USER \
        --exec $DAEMON $ARGS
    ;;
  stop)
    echo "Stopping server"
    /sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose
    ;;
  *)
    echo "Usage: /etc/init.d/$USER {start|stop}"
    exit 1
    ;;
esac

exit 0

and in python: 并在python中:

import signal
import time
import multiprocessing

stop_event = multiprocessing.Event()

def stop(signum, frame):
    stop_event.set()

signal.signal(signal.SIGTERM, stop)

if __name__ == '__main__':
    while not stop_event.is_set():
        time.sleep(3)

My question now is if this approach is correct. 我现在的问题是这种方法是否正确。 Do I have to handle any additional signals? 我是否必须处理任何其他信号? Will it be a "well-behaved Unix daemon process"? 它会是一个“表现良好的Unix守护进程”吗?

Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use upstart . 假设您的守护进程有某种持续运行的方式(某些事件循环,扭曲,等等),您可以尝试使用upstart

Here's an example upstart config for a hypothetical Python service: 这是一个假设的Python服务的示例upstart配置:

description "My service"
author  "Some Dude <blah@foo.com>"

start on runlevel [234]
stop on runlevel [0156]

chdir /some/dir
exec /some/dir/script.py
respawn

If you save this as script.conf to /etc/init you simple do a one-time 如果将此文件作为script.conf保存到/etc/init ,则只需执行一次

$ sudo initctl reload-configuration
$ sudo start script

You can stop it with stop script . 你可以用stop script来阻止它。 What the above upstart conf says is to start this service on reboots and also restart it if it dies. 以上新贵的说法是在重启时启动此服务,如果它死了也重新启动它。

As for signal handling - your process should naturally respond to SIGTERM . 至于信号处理 - 您的过程应该自然地响应SIGTERM By default this should be handled unless you've specifically installed your own signal handler. 默认情况下,除非您专门安装了自己的信号处理程序,否则应该进行处理。

Rloton's answer is good. Rloton的答案很好。 Here is a light refinement, just because I spent a ton of time debugging. 这是一个轻量级的改进,只是因为我花了很多时间调试。 And I need to do a new answer so I can format properly. 我需要做一个新的答案,这样我才能正确格式化。

A couple other points that took me forever to debug: 还有几个让我永远调试的要点:

  1. When it fails, first check /var/log/upstart/.log 失败时,首先检查/var/log/upstart/.log
  2. If your script implements a daemon with python-daemon , you do NOT use the 'expect daemon' stanza. 如果您的脚本使用python-daemon实现守护程序 ,则不要使用'expect daemon'节。 Having no 'expect' works. 没有“期待”的作品。 I don't know why. 我不知道为什么。 (If anyone knows why - please post!) (如果有人知道原因 - 请发帖!)
  3. Also, keep checking "initctl status script" to make sure you are up (start/running). 此外,继续检查“initctl status script”以确保您已启动(启动/运行)。 (and do a reload when you update your conf file) (并在更新conf文件时重新加载)

Here is my version: 这是我的版本:

description "My service"
author  "Some Dude <blah@foo.com>"

env PYTHON_HOME=/<pathtovirtualenv>
env PATH=$PYTHON_HOME:$PATH

start on runlevel [2345]
stop on runlevel [016]

chdir <directory>

# NO expect stanza if your script uses python-daemon
exec $PYTHON_HOME/bin/python script.py

# Only turn on respawn after you've debugged getting it to start and stop properly
respawn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM