You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派4开机自动运行Python脚本失败求助

解决树莓派4开机自动运行摄像头Python脚本的问题

一、修正cron方法

你的cron命令存在路径输入错误(末尾d>为失误),且cron默认未加载图形环境变量,摄像头调用依赖X11,修正步骤:

  1. 打开cron编辑:crontab -e
  2. 添加以下命令(替换为你的实际脚本路径):
@reboot export DISPLAY=:0 && /usr/bin/python3 /home/raspberrypi/tflite-custom-object-bookworm-main/detect1.py >> /home/raspberrypi/cron_log.txt 2>&1
  • export DISPLAY=:0:指定图形显示端口,确保脚本能访问摄像头和图形输出
  • 日志重定向用于后续排查启动错误

二、修正rc.local方法

你的命令存在路径拼写错误(detect1.p>应为detect1.py),且rc.local运行在用户会话启动前,需切换到pi用户并设置环境变量:

  1. 编辑rc.local:sudo nano /etc/rc.local
  2. 在exit 0前添加:
su - raspberrypi -c "export DISPLAY=:0 && /usr/bin/python3 /home/raspberrypi/tflite-custom-object-bookworm-main/detect1.py &"
  • su - raspberrypi:切换到普通用户运行脚本,避免权限冲突
  • &:让脚本后台运行,不阻塞系统启动流程

三、修正LXSession autostart方法

你的配置存在路径不一致问题(脚本实际在tflite-custom-object-bookworm-main目录,却写了Desktop路径),且sudo可能无必要,修正步骤:

  1. 打开autostart文件:nano ~/.config/lxsession/LXDE-pi/autostart
  2. 添加正确的启动命令:
@lxterminal -e "/usr/bin/python3 /home/raspberrypi/tflite-custom-object-bookworm-main/detect1.py"
  • 若不需要终端窗口显示,可直接写@/usr/bin/python3 /home/raspberrypi/tflite-custom-object-bookworm-main/detect1.py

四、修正systemd方法

你的配置使用了占位符路径,且未适配图形环境,修正后的完整配置:

  1. 创建服务文件:sudo nano /etc/systemd/system/pothole-detect.service
  2. 写入以下内容(替换为实际路径):
[Unit]
Description=Pothole Detection Service
After=graphical.target network.target

[Service]
Type=simple
User=raspberrypi
Environment=DISPLAY=:0
ExecStart=/usr/bin/python3 /home/raspberrypi/tflite-custom-object-bookworm-main/detect1.py
WorkingDirectory=/home/raspberrypi/tflite-custom-object-bookworm-main
StandardOutput=journal+console
StandardError=journal+console
Restart=on-failure

[Install]
WantedBy=graphical.target
  • After=graphical.target:确保桌面环境完全启动后再运行脚本,适配摄像头的图形依赖
  • Environment=DISPLAY=:0:设置图形显示变量
  1. 启用并启动服务:
sudo systemctl daemon-reload
sudo systemctl enable pothole-detect.service
sudo systemctl start pothole-detect.service
  • 用sudo systemctl status pothole-detect.service查看运行状态,排查启动故障

通用排查要点

  • 检查脚本权限:执行chmod +x /home/raspberrypi/tflite-custom-object-bookworm-main/detect1.py赋予可执行权限
  • 验证摄像头权限:确保pi用户属于video组:sudo usermod -aG video raspberrypi
  • 查看日志定位问题:
    • cron日志:cat /home/raspberrypi/cron_log.txt
    • systemd日志:journalctl -u pothole-detect.service

内容的提问来源于stack exchange,提问作者Genesis Coronel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 07:57:13