将python程序注册为Ubuntu系统服务,并开机启动的方法。
一、系统环境
操作系统:ubuntu 18.04以后 (该版本已默认使用systemd作为init)
二、步骤
1、在目录/opt/install下
- 准备python程序 main.py
- 准备sh脚本svc-test.sh
#!/bin/bash
P_HOME=$(cd "$(dirname "$0")";pwd)
echo "P_HOME=$P_HOME"
export PYTHONPATH=/opt/install/dispatchingEnv/lib/python3.8/site-packages //python packages
# export PATH=$PATH:
echo "PYTHONPATH=$PYTHONPATH"
cd $P_HOME
cd src
python3 main.py
cd ../
2、添加执行权限
chmod +x /opt/install/main.py
chmod +x /opt/install/svc-test.sh
(二)向系统注册服务
1、编写注册文件
在 /etc/systemd/system/
下添加svc-test.service 文件
在svc-test.service文件下复制以下内容
[Unit]
Description=svc-test
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=root
ExecStart=/usr/bin/bash /opt/install/svc-test.sh // 必须为绝对路径
[Install]
WantedBy=multi-user.target
2、添加执行权限
chmod + x /etc/systemd/system/svc-test.service
3、重载系统服务
systemctl daemon-reload
4、将服务注册为开机启动
systemctl enable svc-test.service
5.重启服务:sudo reboot
三、附录–一些关于systemctl的命令
查看所有服务的状态
systemctl status
停止服务
systemctl stop svc-test
手工启动服务
systemctl start svc-test
查看单个服务的状态
systemctl status svc-test
禁用开机启动
systemctl disable svc-test.service
参考链接:1.https://www.jianshu.com/p/b75d88e5aa61
2.http://www.manongjc.com/detail/18-cwhjgfrdexqyxof.html