Running Python script via systemd fails to load module

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

User=pi

Refer to the solution of AndyD.


The most likely explanation is that you have some environment variables set (e.g. an extension of your PYTHONPATH?) which is not set when the script is being run by systemd.

You could try using the Environment parameter (see [0]) so set PYTHONPATH (and whatever else might influence this) to whatever it is in your console session.

[0] http://0pointer.de/public/systemd-man/systemd.exec.html#Environment=


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.