Python script as linux service/daemon

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 <[email protected]>"

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.

Leave a Comment