![Systemd 服务无法识别 python 库](https://linux22.com/image/138531/Systemd%20%E6%9C%8D%E5%8A%A1%E6%97%A0%E6%B3%95%E8%AF%86%E5%88%AB%20python%20%E5%BA%93.png)
当我的 Raspberry Pi 启动时,我试图运行一个 python Discord 机器人。为此,我使用了 systemd 服务:
[Unit]
Description=Testing
[Service]
Type=idle
WorkingDirectory=/home/pi
ExecStart=/usr/bin/python3 /home/pi/discord/bug.py
[Install]
WantedBy=multi-user.target
我之前用更简单的Python程序做过几次测试,一切都很好。当尝试运行不和谐机器人时,它会在导入语句中抛出错误。为了测试我运行:
sudo systemctl start bugstart
sudo systemctl status bugstart
状态的输出如下:
bugstart.service - Testing
Loaded: loaded (/lib/systemd/system/bugstart.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Sun 2018-08-12 02:08:47 UTC; 1s ago
Process: 1039 ExecStart=/usr/bin/python3 /home/pi/discord/bug.py (code=exited, status=1/FAILURE)
Main PID: 1039 (code=exited, status=1/FAILURE)
Aug 12 02:08:46 raspberrypi systemd[1]: Started Testing.
Aug 12 02:08:47 raspberrypi python3[1039]: Traceback (most recent call last):
Aug 12 02:08:47 raspberrypi python3[1039]: File "/home/pi/discord/bug.py", line 1, in <module>
Aug 12 02:08:47 raspberrypi python3[1039]: import discord
Aug 12 02:08:47 raspberrypi python3[1039]: ImportError: No module named 'discord'
Aug 12 02:08:47 raspberrypi systemd[1]: bugstart.service: Main process exited, code=exited, status=1/FAILURE
Aug 12 02:08:47 raspberrypi systemd[1]: bugstart.service: Unit entered failed state.
Aug 12 02:08:47 raspberrypi systemd[1]: bugstart.service: Failed with result 'exit-code'.
我发现这些命令是以 root 身份运行的,所以我想可能是库没有安装在 root 上,但我尝试在命令行 shell 中导入不和谐,它工作得很好。
答案1
Systemd 在最小环境下启动进程。在这种情况下,您可能会丢失PYTHONPATH
甚至更多。在命令行上自己尝试一下env
:
env -i /usr/bin/python3 /home/pi/discord/bug.py
您可能会遇到同样的错误。所以现在尝试一下
env -i PYTHONPATH=you-path /usr/bin/python3 /home/pi/discord/bug.py
如果这有效,请添加
Environment=PYTHONPATH=you-path
到您的 systemd 单元。
如果它不起作用,您需要找出还需要什么。