Python script as linux service/daemon

前端 未结 2 1137
谎友^
谎友^ 2020-11-28 17:29

Hallo,

I\'m trying to let a python script run as service (daemon) on (ubuntu) linux.

On the web there exist several solutions like:

http://pypi.pytho

相关标签:
2条回答
  • 2020-11-28 18:15

    Rloton's answer is good. 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
    2. If your script implements a daemon with python-daemon, you do NOT use the 'expect daemon' stanza. 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). (and do a reload when you update your conf file)

    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
    
    0 讨论(0)
  • 2020-11-28 18:21

    Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use upstart.

    Here's an example upstart config for a hypothetical Python service:

    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

    $ sudo initctl reload-configuration
    $ sudo start script
    

    You can stop it with 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. By default this should be handled unless you've specifically installed your own signal handler.

    0 讨论(0)
提交回复
热议问题