Example of python service running under systemd?

Chris Angelico rosuav at gmail.com
Fri Sep 12 02:06:59 CEST 2014


On Fri, Sep 12, 2014 at 3:48 AM, Travis Griggs <travisgriggs at gmail.com> wrote:
> I’ve been reading lots of systemd docs. And blogs. Etc. At this point, I think I would benefit from learning by example…
>
> Does anyone have an example .service file that they use to launch a long running service written as a python program?
>
> If there is any example of what you changed to your python program itself, that to would be really instructional for me.

Yeah, I did that for the Yosemite Project:

https://github.com/Rosuav/Yosemite

The main program is Python, but all the systemd code comes from a Pike
script that creates a bash script that creates the systemd file. Yes,
that's a little convoluted... Here's the relevant shell script part,
in case you don't want to dig it out of auth.pike:


#!/bin/bash
[ "$1" = "install" ] && [ -d /etc/systemd/system ] && {
    echo "[Unit]
Description=Yosemite Project

[Service]
# The user, path, and X display are derived at installation time
# from the attributes of the yos script. Reinstall to reset them.
Environment=DISPLAY=$DISPLAY
User=`stat -c %u $0`
ExecStart=`readlink -e $0`
# If the network isn't available yet, restart until it is.
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
" >/etc/systemd/system/yos.service
    # Note that some of this will fail if systemd is installed
    # but isn't the default init system. In that case, well, you
    # can't use this method of autostarting. TODO: Provide some
    # other ways to autostart (eg for Upstart and/or sysvinit).
    systemctl --system daemon-reload
    systemctl enable yos.service
    echo Installed as yos.service.
    systemctl start yos.service
    exit
}
# ... blah blah various setup
python Yosemite.py


This has some complications that you probably don't need, like that
the owner of the script should become the user that runs it (chances
are you can hard-code this, or run it as root and have it drop
privileges itself, or something), and it needs to restart on failure,
as it has to establish an sshfs mount before starting the main
program. But it's a start.

Note the three commands just before the script exits. Unlike sysvinit
and upstart, systemd needs to be told to reload service files, and
then you need to enable the service before it'll run on startup (and I
like to start it immediately, to see that it's working properly). Took
me a few hang-ups to figure that part out. Fortunately systemd can
notice and give a warning if you change files and don't daemon-reload
it; I'm not sure why it can't simply reload automatically (AIUI
Upstart uses inotify on /etc/init - no idea why systemd can't do the
same).

ChrisA



More information about the Python-list mailing list