Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Python script via systemd fails to load module

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.

like image 939
Shiri Avatar asked Jul 22 '16 13:07

Shiri


2 Answers

Add this property to [Service] section to make sure systemd run as the specified user.

User=pi

Refer to the solution of AndyD.

like image 70
Itachi Avatar answered Sep 21 '22 12:09

Itachi


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.

like image 43
Shiri Avatar answered Sep 18 '22 12:09

Shiri