Running Python script via systemd fails to load module

Shiri picture Shiri · Jul 22, 2016 · Viewed 9.8k times · Source

I have a Python script that uses zmq and I've installed this library via pip install zmq and I can run the program fine if called manually via the command line. However as soon as I attempt to have a systemd unit call the script, running systemctl status myservice.service shows ImportError: No module named zmq.

My service file looks like this:

[Unit]
Description=Does Something

[Service]
Type=simple
ExecStart=/bin/sh /var/lib/project/runpythonscript.sh
Restart=always

[Install]
Alias=myservice.service

Where runpythonscript.sh is a very simple shell script that runs my python script as root. Running this shell script manually from the command line runs my python program completely fine but having the service call it causes it to not locate the zmq module.

Any help is appreciated.

Answer

Shiri picture Shiri · Jul 22, 2016

systemd runs as root. The modules installed via pip are installed for a user rather than for the system and so installing the modules without root privileges made the modules unaccessible for root.

To solve this I ran sudo -H pip install zmq and sudo -H pip3 install zmq to install the packages for both Python 2.7 and Python 3+ for root. This allowed systemd to access the modules once it attempts to execute the Python script.