树莓派 开机启动python脚本的一种方法

某宝上买了一个小oled屏用来在树莓派上显示一些简短信息,需要开机启动,但很久才会设置一次,记下备查:

1、写个开机启动脚本,放在/etc/init.d/下,比如:/etc/init.d/minioled

 

#!/bin/bash
# /etc/init.d/minioled

### BEGIN INIT INFO
# Provides: laonan
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: minioled initscript
# Description: This service is used to manage a minioled
### END INIT INFO

case "$1" in
    start)
        echo "Starting mini OLED"
        python /home/pi/script/minioled.py &
        ;;
    stop)
        echo "Stopping mini OLED"
        #killall minioled.py
        kill $(ps aux | grep -m 1 'python /home/pi/script/minioled.py' | awk '{ print $2 }')
        ;;
    *)
        echo "Usage: service minioled start|stop"
        exit 1
        ;;
esac
exit 0

2、设置开机启动

chmod +x /etc/init.d/minioled

3、然后

sudo service minioled start # 启动
sudo service minioled stop # 停止
sudo update-rc.d minioled defaults # 设置开机启动

sudo systemctl start minioled # 启动
sudo systemctl stop minioled # 停止
sudo systemctl restart minioled # 重启
sudo systemctl enable minioled # 设置开机启动

我更习惯用Systemd工具

参考:https://blog.csdn.net/b108074013/article/details/47443871

树莓派 开机启动 python脚本
Views (3508) Comments (2) 2019-06-03
老楠 :
### BEGIN INIT INFO ... ### END INIT INFO 这一段不能省略,否则会报类似下面这种错: pdate-rc.d: error: minioled contains no runlevels, aborting.
老楠 :
设置完不行,重启一下就行了,不知道为啥。。。可能是不行之后chmod 777 xxx.py了一次? 另外,网上改/etc/rc.local那种方法更简单,但是比如你要跑一个服务,然后同时还要用UI的话,这种方式可能略强。当然修改rc.local也可以,记得后面加一个& ,如:python /home/pi/myscript.py &
For example, "name@something.com". If someone replies to you it will be via email.
For example, "http://someaddress.com"