Loading

Systemd 添加自定义python启动项 报错 导入包错误

1. Systemd介绍

systemd是Linux电脑操作系统之下的一套中央化系统及设置管理程序(init),包括有守护进程、程序库以及应用软件,由Lennart Poettering(英语:Lennart Poettering)带头开发。其开发目标是提供更优秀的框架以表示系统服务(英语:Service (systems architecture))间的依赖关系,并依此实现系统初始化时服务的并行启动,同时达到降低Shell的系统开销(英语:Computational overhead)的效果,最终代替现在常用的System V与BSD风格init程序。
Systemd 并不是一个命令,而是一组命令,涉及到系统管理的方方面面:
image

2. 将Python程序加入开机启动启动服务

创建 /etc/systemd//system下面的xxx.service, 以我的为例/etc/systemd/system/autorecord.service,写入如下内容。

[Unit]

Description=Files Service

After=multi-user.target

[Service]

Type=idle
ExecStart=/usr/bin/python3 /home/aitest/cv.py
Environment="PYTHON=$PYTHONPATH:/home/test/.local/lib/python3.8/site-packages"
Restart=always

[Install]

WantedBy=multi-user.target
  • 然后重新加载 systemd
sudo systemctl daemon-reload
  • 设置服务开机 自动启动
sudo systemctl enable autorecord.service

3. 报错内容

加入python程序需要导入第三方包,那么会报导入错误。如下:

autorecord2.service - Files Service
     Loaded: loaded (/etc/systemd/system/autorecord2.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2022-05-17 22:28:58 CST; 11h ago
   Main PID: 2251 (code=exited, status=1/FAILURE)

5月 17 22:28:58 aitest-System-Product-Name systemd[1]: Started Files Service.
5月 17 22:28:58 aitest-System-Product-Name python3[2251]: Traceback (most recent call last):
5月 17 22:28:58 aitest-System-Product-Name python3[2251]:   File "/home/aitest/cv1.py", line 7, in <modul>
5月 17 22:28:58 aitest-System-Product-Name python3[2251]:     import ffmpeg_streaming
5月 17 22:28:58 aitest-System-Product-Name python3[2251]: ModuleNotFoundError: No module named 'ffmpeg_st>
5月 17 22:28:58 aitest-System-Product-Name systemd[1]: autorecord2.service: Main process exited, code=exi>
5月 17 22:28:58 aitest-System-Product-Name systemd[1]: autorecord2.service: Failed with result 'exit-code>

可以通过添加PYTHONPATH环境变量解决(上面示例已添加):

Environment="PYTHON=$PYTHONPATH:/home/test/.local/lib/python3.8/site-packages"

4. 参考资料

关于.service文件的详细配置见 阮一峰的网络日志-Systemd 入门教程:命令篇

posted @ 2022-05-18 11:44  Geoffrey_one  阅读(222)  评论(0编辑  收藏  举报
/*
*/