ImportError: No module named 'schedule' when i using system to run a service

ImportError: No module named 'schedule' when i using system to run a service

我写了一个名为 coinview.py 的脚本,它可以在 linux 上 运行。当我尝试 运行 它作为 systemd 时,它会引发错误

error:ImportError: No module named 'schedule'.

我用pip3显示时间表,它已经存在了。所以我不知道我的脚本有什么问题。

我在 systemd 中打印 sys.executable 和 sys.path。

[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: mail@dbader.org
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

安装 root 包

sudo pip install schedule

或者不以 root 运行 身份,尝试以另一个特定用户身份 运行 。 将您的 .service 修改为:

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

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

[Install]
WantedBy=multi-user.target

希望对您有所帮助!

根据这些日志,我发现手册中的 PYTHONPATH 不同 shell 和 systemd.And 我尝试添加“/home/ubuntu/.local/lib/python3.5/ site-packages" 到 /etc/profile 但 systemd 日志显示它仍然找不到路径。

所以我做了一件小事,添加

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

在我的代码中,它有效...