
- 第一步,先给你的 Python 脚本加上执行权限。用
chmod搞定:
chmod +x /path/to/your/python_script.py
- 接着,创建一个 systemd 服务文件。用
nano或vim打开一个新文件,路径为/etc/systemd/system/my_python_service.service,把下面这些内容贴进去:
[Unit]
Description=My Python Service
After=network.target
[Service]
Type=simple
User=
Group=
WorkingDirectory=/path/to/your/script/directory
ExecStart=/usr/bin/python3 /path/to/your/python_script.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
注意把 和 换成实际运行脚本的用户和组,/path/to/your/python_script.py 换成脚本的真实路径。
- 然后,让 systemd 重新加载配置:
sudo systemctl daemon-reload
- 启动刚定义的服务:
sudo systemctl start my_python_service
- 检查服务是否正常运行:
sudo systemctl status my_python_service
如果状态显示 active (running),说明脚本已经成功跑起来了。
- 想让它在系统启动时自动启动?执行:
sudo systemctl enable my_python_service
- 需要停止或重启服务,用这两个命令:
sudo systemctl stop my_python_service
sudo systemctl restart my_python_service
最后多说一句:以上步骤默认用的是 Python 3(路径 /usr/bin/python3)。如果你还在用 Python 2,记得把路径换成 /usr/bin/python2。