树莓派上通过 systemd 配置 Python 程序开机自动启动的 详细教程
以下是在树莓派上通过 systemd 配置 Python 程序开机自动启动的 详细教程包含 服务文件编写、日志管理、权限设置、故障排查 等关键步骤确保你的 Python 程序能稳定运行。1. 准备工作1.1 确认 Python 程序可独立运行确保你的 Python 程序如main.py能在终端手动运行python3 /path/to/your/main.py如果程序依赖虚拟环境先激活虚拟环境测试source /path/to/venv/bin/activate python3 main.py1.2 创建工作目录推荐建议将程序和相关文件放在统一目录如/home/pi/my_python_servicemkdir -p /home/pi/my_python_service cp main.py /home/pi/my_python_service/2. 编写 systemd 服务文件2.1 服务文件模板在/etc/systemd/system/下创建服务文件如my_python_service.servicesudo nano /etc/systemd/system/my_python_service.service填写以下内容根据实际需求修改[Unit] DescriptionMy Python Service # 服务描述 Afternetwork.target # 依赖网络就绪后启动 Wantsnetwork-online.target # 可选更严格的网络依赖 [Service] Typesimple # 服务类型simple/forking/oneshot Userpi # 运行用户避免用root Grouppi # 运行用户组 WorkingDirectory/home/pi/my_python_service # 工作目录 ExecStart/usr/bin/python3 /home/pi/my_python_service/main.py # 启动命令 Restartalways # 崩溃后自动重启 RestartSec5 # 重启间隔秒 StandardOutputsyslog # 输出日志到syslog StandardErrorsyslog # 错误日志到syslog SyslogIdentifierpython-app # 日志标识符 # 可选环境变量设置 EnvironmentPYTHONPATH/home/pi/my_python_service EnvironmentPYTHONUNBUFFERED1 # 禁用输出缓冲实时查看日志 # 可选资源限制 LimitNOFILE65536 LimitNPROC4096 [Install] WantedBymulti-user.target # 多用户模式下启用2.2 关键参数说明表格参数作用Typesimple默认类型适用于大多数 Python 程序Restartalways程序崩溃后自动重启Userpi避免用 root 运行提高安全性WorkingDirectory程序的工作目录影响相对路径SyslogIdentifier日志标识符方便过滤日志3. 配置并启用服务3.1 重新加载 systemd 配置sudo systemctl daemon-reload3.2 启用服务开机自启sudo systemctl enable my_python_service.service3.3 立即启动服务可选sudo systemctl start my_python_service.service4. 管理服务4.1 检查服务状态sudo systemctl status my_python_service.service绿色active (running) 表示运行正常。红色failed 表示启动失败需查看日志排查。4.2 查看日志# 实时查看日志 sudo journalctl -u my_python_service.service -f # 查看最近日志 sudo journalctl -u my_python_service.service --no-pager -n 504.3 停止/重启服务sudo systemctl stop my_python_service.service sudo systemctl restart my_python_service.service5. 常见问题排查5.1 服务启动失败检查日志sudo journalctl -u my_python_service.service -b常见原因路径错误ExecStart或WorkingDirectory路径不正确。权限问题程序需要访问的文件/目录权限不足。依赖缺失程序依赖的库未安装如numpy、opencv。虚拟环境未激活如果程序依赖虚拟环境需在ExecStart中指定虚拟环境的 Python 路径ExecStart/home/pi/venv/bin/python3 /home/pi/my_python_service/main.py5.2 日志无输出确保StandardOutput和StandardError设置为syslog或journal。在 Python 代码中强制刷新输出适用于print不显示的情况import sys print(Debug message, flushTrue) # 强制刷新输出5.3 程序崩溃后不重启检查Restart策略是否设置为always或on-failure。确保程序没有陷入死循环导致systemd认为仍在运行。6. 完整示例6.1 Python 程序main.pyimport time import logging from datetime import datetime # 配置日志可选也可依赖systemd的syslog logging.basicConfig( levellogging.INFO, format%(asctime)s - %(levelname)s - %(message)s, handlers[ logging.FileHandler(/home/pi/my_python_service/app.log), logging.StreamHandler() ] ) def main(): logging.info(Python服务启动) try: while True: logging.info(f服务运行中... {datetime.now()}) time.sleep(10) except Exception as e: logging.error(f服务异常: {e}) raise if __name__ __main__: main()6.2 服务文件/etc/systemd/system/my_python_service.service[Unit] DescriptionMy Python Service Afternetwork.target [Service] Typesimple Userpi Grouppi WorkingDirectory/home/pi/my_python_service ExecStart/usr/bin/python3 /home/pi/my_python_service/main.py Restartalways RestartSec5 StandardOutputsyslog StandardErrorsyslog SyslogIdentifierpython-app [Install] WantedBymulti-user.target6.3 部署步骤# 1. 创建目录并复制程序 mkdir -p /home/pi/my_python_service cp main.py /home/pi/my_python_service/ # 2. 创建服务文件 sudo nano /etc/systemd/system/my_python_service.service # 粘贴上述服务文件内容 # 3. 重新加载并启用服务 sudo systemctl daemon-reload sudo systemctl enable my_python_service.service sudo systemctl start my_python_service.service # 4. 检查状态 sudo systemctl status my_python_service.service总结systemd 是树莓派管理后台服务的标准方式比crontab reboot更可靠。关键点正确配置ExecStart和WorkingDirectory。使用Restartalways确保崩溃后自动恢复。通过journalctl查看日志排查问题。扩展如果需要 GUI 程序改用Typeforking并配置PIDFile。如果程序需要网络添加Afternetwork-online.target和Wantsnetwork-online.target。按此教程配置后你的 Python 程序将在树莓派启动时自动运行并在崩溃后自动恢复适合长期运行的物联网、监控等应用场景。