news 2026/4/26 9:53:00

树莓派上通过 ‌systemd‌ 配置 Python 程序开机自动启动的 ‌详细教程

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
树莓派上通过 ‌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.py

1.2 创建工作目录(推荐)

  • 建议将程序和相关文件放在统一目录(如/home/pi/my_python_service):
    mkdir -p /home/pi/my_python_service cp main.py /home/pi/my_python_service/

2. 编写 systemd 服务文件

2.1 服务文件模板

/etc/systemd/system/下创建服务文件(如my_python_service.service):

sudo nano /etc/systemd/system/my_python_service.service

填写以下内容(根据实际需求修改):

[Unit] Description=My Python Service # 服务描述 After=network.target # 依赖网络就绪后启动 Wants=network-online.target # 可选:更严格的网络依赖 [Service] Type=simple # 服务类型(simple/forking/oneshot) User=pi # 运行用户(避免用root) Group=pi # 运行用户组 WorkingDirectory=/home/pi/my_python_service # 工作目录 ExecStart=/usr/bin/python3 /home/pi/my_python_service/main.py # 启动命令 Restart=always # 崩溃后自动重启 RestartSec=5 # 重启间隔(秒) StandardOutput=syslog # 输出日志到syslog StandardError=syslog # 错误日志到syslog SyslogIdentifier=python-app # 日志标识符 # 可选:环境变量设置 Environment="PYTHONPATH=/home/pi/my_python_service" Environment="PYTHONUNBUFFERED=1" # 禁用输出缓冲,实时查看日志 # 可选:资源限制 LimitNOFILE=65536 LimitNPROC=4096 [Install] WantedBy=multi-user.target # 多用户模式下启用

2.2 关键参数说明

表格

参数作用
Type=simple默认类型,适用于大多数 Python 程序
Restart=always程序崩溃后自动重启
User=pi避免用 root 运行,提高安全性
WorkingDirectory程序的工作目录(影响相对路径)
SyslogIdentifier日志标识符,方便过滤日志

3. 配置并启用服务

3.1 重新加载 systemd 配置

sudo systemctl daemon-reload

3.2 启用服务(开机自启)

sudo systemctl enable my_python_service.service

3.3 立即启动服务(可选)

sudo systemctl start my_python_service.service

4. 管理服务

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 50

4.3 停止/重启服务

sudo systemctl stop my_python_service.service sudo systemctl restart my_python_service.service

5. 常见问题排查

5.1 服务启动失败

  1. 检查日志‌:
    sudo journalctl -u my_python_service.service -b
  2. 常见原因‌:
    • 路径错误‌:ExecStartWorkingDirectory路径不正确。
    • 权限问题‌:程序需要访问的文件/目录权限不足。
    • 依赖缺失‌:程序依赖的库未安装(如numpyopencv)。
    • 虚拟环境未激活‌:如果程序依赖虚拟环境,需在ExecStart中指定虚拟环境的 Python 路径:
      ExecStart=/home/pi/venv/bin/python3 /home/pi/my_python_service/main.py

5.2 日志无输出

  • 确保StandardOutputStandardError设置为syslogjournal
  • 在 Python 代码中强制刷新输出(适用于print不显示的情况):
    import sys print("Debug message", flush=True) # 强制刷新输出

5.3 程序崩溃后不重启

  • 检查Restart策略是否设置为alwayson-failure
  • 确保程序没有陷入死循环导致systemd认为仍在运行。

6. 完整示例

6.1 Python 程序(main.py

import time import logging from datetime import datetime # 配置日志(可选,也可依赖systemd的syslog) logging.basicConfig( level=logging.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] Description=My Python Service After=network.target [Service] Type=simple User=pi Group=pi WorkingDirectory=/home/pi/my_python_service ExecStart=/usr/bin/python3 /home/pi/my_python_service/main.py Restart=always RestartSec=5 StandardOutput=syslog StandardError=syslog SyslogIdentifier=python-app [Install] WantedBy=multi-user.target

6.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更可靠。
  • 关键点‌:
    • 正确配置ExecStartWorkingDirectory
    • 使用Restart=always确保崩溃后自动恢复。
    • 通过journalctl查看日志排查问题。
  • 扩展‌:
    • 如果需要 GUI 程序,改用Type=forking并配置PIDFile
    • 如果程序需要网络,添加After=network-online.targetWants=network-online.target

按此教程配置后,你的 Python 程序将在树莓派启动时自动运行,并在崩溃后自动恢复,适合长期运行的物联网、监控等应用场景。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/18 14:41:35

md2pptx:当Markdown遇见结构化思维,演示文稿的范式转换

md2pptx:当Markdown遇见结构化思维,演示文稿的范式转换 【免费下载链接】md2pptx Markdown To PowerPoint converter 项目地址: https://gitcode.com/gh_mirrors/md/md2pptx 你是否曾思考过,为什么技术文档与演示文稿之间总存在难以逾…

作者头像 李华
网站建设 2026/4/19 11:18:20

NVIDIA Profile Inspector终极指南:解锁显卡隐藏性能的简单方法

NVIDIA Profile Inspector终极指南:解锁显卡隐藏性能的简单方法 【免费下载链接】nvidiaProfileInspector 项目地址: https://gitcode.com/gh_mirrors/nv/nvidiaProfileInspector NVIDIA Profile Inspector是一款强大的显卡配置管理工具,它让你能…

作者头像 李华
网站建设 2026/4/18 22:46:33

【人工智能:Agent】--Agent Skills详解

网址:Overview - Agent Skills github: GitHub - agentskills/agentskills: Specification and documentation for Agent Skills GitHub 目录 1.Agent Skills--定义 2.Agent Skills--运行 3.Agent Skills--SKILL.md 3..1.前置元数据 3.2.name …

作者头像 李华
网站建设 2026/4/18 15:25:03

带宽网速、局域网网速测试(亲测)

假设服务器IP是:192.168.1.10一、在线环境安装 iperf3适用于 Ubuntu:apt update apt install -y iperf3验证:iperf3 -v适用于 CentOS 7:yum install -y epel-release yum install -y iperf3CentOS 8 / Rocky / AlmaLinux&#xff…

作者头像 李华
网站建设 2026/4/18 18:53:30

揭秘DeepSeek提示词背后的AI魔法:如何让AI完美扮演100+角色

揭秘DeepSeek提示词背后的AI魔法:如何让AI完美扮演100角色 当你在聊天框中输入"扮演一位资深心理咨询师",几秒后AI便开始用专业术语分析你的情绪状态;切换成"用脱口秀演员的风格讲个笑话",它又能立刻转换语气…

作者头像 李华