Skip to content Skip to sidebar Skip to footer

Python Import Of Local Module Failing When Run As Systemd/systemctl Service

I have a python application that I'm tring to run as a system service. The application runs fine when I run it manually. When I run it as a service it fails to find a local module

Solution 1:

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=<user>
ExecStart=/home/<user>/heartbeat.py
Restart=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.

Solution 2:

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

[Unit]Description=web server monitor

[Service]WorkingDirectory=/home/user/
User=user
ExecStart=/home/user/heartbeat.py
Restart=always
Environment="PYTHONPATH=$PYTHONPATH:/home/nvidia/.local/lib/python3.6/site-packages"[Install]WantedBy=multi-user.target

Solution 3:

First try the following in python prompt.

$ python
>>> import my_mod
Traceback(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

Solution 4:

If you do want to run the service as root, you have to install the module with sudo: sudo pip install my_module.

Solution 5:

1) Install the supervisor package (more verbose instructions here):

sudo apt-get install supervisor

2) Create a config file for your daemon at /etc/supervisor/conf.d/my_mod.conf:

[program:my_mod]directory=/path/to/project/root
environment=ENV_VARIABLE=example,OTHER_ENV_VARIABLE=example2
command=python my_mod.py
autostart=trueautorestart=true

3) Restart supervisor to load your new .conf

supervisorctl update
supervisorctl restart my_mod

Post a Comment for "Python Import Of Local Module Failing When Run As Systemd/systemctl Service"