Python – Import error: No module named ‘schedule’ when i using system to run a service

Import error: No module named ‘schedule’ when i using system to run a service… here is a solution to the problem.

Import error: No module named ‘schedule’ when i using system to run a service

I wrote a script called coinview.py that runs on Linux. When I try to run it as systemd, it throws an error

Error:

ImportError: There is no module named "schedule".

I use pip3 show schedule and it already exists. So I don’t know what’s wrong with my script.

I print sys.executable and sys.path in systemd.

[Unit]
Description=coinview deamon
After=rc-local.service

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/home/ubuntu/source/quotation_api
ExecStart=/usr/bin/python3 coinview.py
Restart=always

[Install]
WantedBy=multi-user.target
ubuntu@ip-100-00-40-02:/etc/systemd/system$ pip3 show schedule
Name: schedule
Version: 0.6.0
Summary: Job scheduling for humans.
Home-page: https://github.com/dbader/schedule
Author: Daniel Bader
Author-email: [email protected]
License: MIT
Location: /home/ubuntu/.local/lib/python3.5/site-packages
Requires: 
Required-by: 

Mar 27 08:40:10 ip-100-00-40-02 python3[8634]: Traceback (most recent call last):
Mar 27 08:40:10 ip-100-00-40-02 python3[8634]:   File "coinview.py", line 3, in <module>
Mar 27 08:40:10 ip-100-00-40-02 python3[8634]:     import requests,threading,time,schedule,json
Mar 27 08:40:10 ip-100-00-40-02 python3[8634]: ImportError: No module named 'schedule'
Mar 27 08:40:10 ip-100-00-40-02 systemd[1]: coinview.service: Main process exited, code=exited, status=1/FAILURE
Mar 27 08:40:10 ip-100-00-40-02 systemd[1]: coinview.service: Unit entered failed state.
Mar 27 08:40:10 ip-100-00-40-02 systemd[1]: coinview.service: Failed with result 'exit-code'.
Mar 27 08:40:10 ip-100-00-40-02 systemd[1]: coinview.service: Service hold-off time over, scheduling restart.
Mar 27 08:40:10 ip-100-00-40-02 systemd[1]: Stopped coinview deamon.
Apr 09 07:59:03 ip-100-00-40-02 python[12095]: /usr/bin/python3
Apr 09 07:59:03 ip-100-00-40-02 python[12095]:  ['/home/ubuntu/source/quotation_api', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x8

Solution

BASED ON THESE LOGS, I FOUND THAT PYTHONPATH IS DIFFERENT IN MANUAL SHELL AND SYSTEMD. I tried adding “/home/ubuntu/.local/lib/python3.5/site-packages” to /etc/profile, but the systemd log shows that it still can’t find the path.

So I did a stuip thing, add

sys.path.append("/home/ubuntu/.local/lib/python3.5/site-packages") 

In my code, it works….

Related Problems and Solutions