python import of local module failing when run as systemd/systemctl service python import of local module failing when run as systemd/systemctl service python python

python import of local module failing when run as systemd/systemctl service


I had a very similar issue converting an upstart heartbeat.conf to a systemd heartbeat.service, except with the requests module. The solution was to specify in the new .service what user to run it as:

[Unit]Description=web server monitor[Service]WorkingDirectory=/home/user/User=userExecStart=/home/user/heartbeat.pyRestart=always[Install]WantedBy=multi-user.target

Without the User=user, I was getting in the journalctl:

systemd[1]: Started web server monitor.heartbeat.py[26298]: Traceback (most recent call last):heartbeat.py[26298]:   File "/home/user/heartbeat.py", line 2, in <heartbeat.py[26298]:     import requestsheartbeat.py[26298]: ImportError: No module named requestssystemd[1]: heartbeat.service: Main process exited, code=exited, status=1/FAILUREsystemd[1]: heartbeat.service: Unit entered failed state.


Add the python site packages environment variable to the systemctl *. Service file

[Unit]Description=web server monitor[Service]WorkingDirectory=/home/user/User=userExecStart=/home/user/heartbeat.pyRestart=alwaysEnvironment="PYTHONPATH=$PYTHONPATH:/home/nvidia/.local/lib/python3.6/site-packages"[Install]WantedBy=multi-user.target


First try the following in python prompt.

$ python>>> import my_modTraceback (most recent call last):File "<stdin>", line 1, in <module>ImportError: No module named my_mod>>>

Fix 1

If you are getting the above sort of output then the cause may be because of permission issue. Grant permission for site-packages using the following.

sudo chmod -R go+rX /usr/local/lib/python2.7/dist-packages

Fix 2

Try exporting the PYTHONPATH as below:

export PYTHONPATH="/usr/.local/lib/python2.7/site-packages"

Fix 3

Check if you have multiple version of python running in same machine.

If so, check whether you have proper interpreter is included at the beginning of the code like #!/usr/bin/python