树莓派Raspberry设置python脚本开机启动

最近有个项目利用树莓派来完成,主要是在树莓派上用python写了个脚本来处理一些信息与逻辑。这边就遇到一个问题,即设置该脚本在开机的时候自动运行,而不是需要人登陆到树莓派上在执行这个程序,这样太麻烦了,顶多在实验室玩玩,拿不出去。本文主要讲诉设置该python脚本在树莓派上自动运行。

个人原创,版权所有,转载请注明原文出处,并保留原文链接:

https://www.embbnux.com/2015/04/12/raspberry_pi_setting_python_script_start_on_boot/

   一、首先写个简单的python 脚本

脚本很简单,就是树莓派上一个灯闪烁程序,需要学gpio可以看我之前的博客

文件保存在/home/pi/script/ledblink.py

#!/usr/bin/env python

from gpiozero import LED
from time import sleep

led = LED(21) # GPIO 21
while True:
  try:
    led.on()
    sleep(1)
    led.off()
    sleep(1)
  except (KeyboardInterrupt, SystemExit):
    led.off()
    print("led exit")
    break

 二 开机启动脚本

保存以下代码为 /etc/systemd/system/ledblink.service 文件

[Unit]
Description=LED blink service
after=network.target

[Service]
ExecStart=/usr/bin/python3 -u /home/pi/script/ledblink.py
WorkingDirectory=/home/pi/script
StandardOutput=inherit
StandardOutput=inherit
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

三 设置python脚本开机启动

sudo systemctl daemon-reload

这样启动该脚本用service 命令就可以

sudo service ledblink start#启动
sudo service ledblink stop#停止

最后设置开机启动就好了

sudo systemctl enable ledblink.service

禁止开机启动:

sudo systemctl disable ledblink.service

这样就完工了,重启树莓派就会发现led自己闪烁了,停止用sudo service ledblink stop就行

参考: Systemd

《树莓派Raspberry设置python脚本开机启动》上有11条评论

    1. 只是把博主的/home/pi/script/ledblink.py文件内容改成简单的print “haha”语句,其余步骤都一样,有两个疑惑点,望解答:
      1)sudo service ledblink start 无法启动服务,需运行/etc/init.d/ledblink start ,这跟版本相关?还是什么?
      2)reboot之后再次进入系统,并没有打印语句,这意味着服务并没有自启动吧,不知道问题出在哪?

  1. 你好,成功运行了,但是如何取消这个自启动程序?
    我现在是把脚本直接删除了,是可行的,但不知有无其它方法

  2. 在树莓派论坛上看到一个不错的方法,和大家分享一下。
    1. ledblink.py 文件放在/home/pi/
    2. sudo nano /etc/profile
    3. 复制到profile中:sudo python /home/pi/ledblink.py

    注:nano 也可以换成thonny 。

回复 Embbnux 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Time limit is exhausted. Please reload the CAPTCHA.

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据