文章
Linux设置自启动脚本(systemd方式)
2026年5月31日
5 min read
linux systemd python
Linux设置开机自启动脚本
systemd方式将Python脚本注册为一个系统服务,可以精确控制其运行方式、自动重启、日志记录等,非常适合长期运行的后台程序或服务器应用。
操作步骤#
- 创建你的Python脚本 首先,确保你的Python脚本是可执行的,并记录下它的绝对路径。例如,假设脚本位于 /home/yourusername/myscript.py。 注意:如果你的脚本需要特定的Python虚拟环境,请在服务文件中使用虚拟环境内python解释器的绝对路径。
- 创建一个 systemd 服务单元文件 使用sudo权限在/etc/systemd/system/目录下创建一个以.service结尾的文件。文件名将作为你的服务名,例如my-python-script.service。
- sudo vim /etc/systemd/system/my-python-script.service
- 编辑服务文件 将以下内容复制并粘贴到文件中,根据你的实际情况修改关键路径和用户名。
[Unit]
Description=robot dog control
After=network.target
[Service]
Type=simple
User=pi
WorkingDirectory=/home/pi/control_dog_server
ExecStart=/usr/bin/python3 /home/pi/control_dog_server/main_server.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.targetini- 保存并退出编辑器
配置说明:
- Description:服务的简单描述,可以自定义。
- After=network.target:表示在网络服务启动后再启动此脚本,适用于需要联网的脚本。
- User:指定运行脚本的系统用户,为了安全,建议使用普通用户而非root。
- WorkingDirectory:设置脚本的工作目录。
- ExecStart:这是最关键的一行,格式为 [Python解释器路径] [你的脚本绝对路径]。你可以通过which python3命令查找Python解释器路径。
- Restart=always:设置脚本无论因何种原因退出,都会自动重启,保证服务持久运行。
- RestartSec=10:重启前等待10秒,防止因频繁崩溃而导致资源耗尽。
- WantedBy=multi-user.target:定义该服务在系统进入多用户模式(即正常启动)时被启动
-
重新加载systemd,使其识别新的服务文件 sudo systemctl daemon-reload
-
将服务设置为开机自启 sudo systemctl enable my-python-script.service
-
立即启动服务(无需重启即可测试) sudo systemctl start my-python-script.service
-
实时追踪日志 sudo journalctl -u my-python-script.service -f
-
修改配置文件后需要重新加载 sudo systemctl daemon-reload sudo systemctl restart my-python-script.service sudo systemctl status my-python-script.service # 查看状态