step 1 第一步,编写脚步执行文件
vim start_script.sh
我的目录是/home/hope-new/picsevrer 大家根据自己目录参考,因为我是Jetson 需要虚拟环境,因此 source 命令
内容如下
#!/bin/bash
source /home/hope-new/picserver/bin/activate
cd /home/hope-new/picserver
exec python yourpythonfile.py
and next step : 让文件成为可执行文件
chmod +x start_script.sh
step 2 第二步,编写.service后缀文件
sudo vim /etc/systemd/system/hope.service
我的文件名称是hope.service
内容如下,
[Unit]
Description=My Python Script
[Service]
ExecStart=/home/hope-new/start_script.sh
WorkingDirectory=/home/hope-new/picserver
# 重启服务时等待进程正常退出
KillMode=process
# 设置环境变量(如果需要的话)
Environment="PATH=/home/hope-new/picserver/bin:$PATH"
# 确保服务在退出时重启
Restart=always
[Install]
WantedBy=multi-user.target
step 3 生效
sudo systemctl enable hope.service
sudo systemctl start hope.service
可以查看运行状态
sudo systemctl status hope.service