树莓派设置开机自启动的三种方式

2026-01-03 16:55:11 | 第一次世界杯 | admin | 5201°c

一. 配置rc.local文件方式

编辑/etc/rc.local文件

sudo vi /etc/rc.local

在文件中exit 0 之前添加需要执行的命令,文件路径使用绝对路径,如:

#!/bin/sh -e

#

# rc.local

#

# This script is executed at the end of each multiuser runlevel.

# Make sure that the script will "exit 0" on success or any other

# value on error.

#

# In order to enable or disable this script just change the execution

# bits.

#

# By default this script does nothing.

# Print the IP address

_IP=$(hostname -I) || true

if [ "$_IP" ]; then

printf "My IP address is %s\n" "$_IP"

fi

/usr/bin/python3 /home/pi/Desktop/testGPIO.py 23 10 &

exit 0

注意:如果程序是阻塞的,则必须加上&符号,表示在后台运行,否则系统无法启动

重启系统,就可以生效了

二. 新建desktop文件设置树莓派开机启动项

这种方式类似Windows系统的"开始"菜单中的"启动"项,操作方法如下:

在/home/pi/.config 文件夹下创建一个文件夹,名称为autostart

mkdir /home/pi/.config/autostart

在该文件夹下创建一个xxx.desktop文件,文件名以.desktop结尾,名称为xxx,可自定义,文件内容如下:

[Desktop Entry]

Name=controller

Comment=controller Program

Encoding=UTF-8

#Exec=python3 /home/pi/human_code/controller.py

Terminal=false

MultipleArgs=false

Type=Application

Categories=Application;Development;

StartupNotify=true

文件中Name,Comment,Icon分别表示启动文件的名称,备注,显示图标,他们的值可以自己设定;

Exec表示调用的指令,相当于在shell终端执行的指令.

重启系统,就可以生效了.

三. 以后台服务的方式设置开机启动程序

创建服务文件 /etc/systemd/system/xxx.service

文件内容如下:

[Unit]

Description=A server for test

After=network.target

[Service]

Type=simple

Restart=always

RestartSec=5

ExecStart=/usr/bin/python3 /home/pi/Desktop/testGPIO.py 23 10

StandarOutput=null

StandarError=null

[Install]

WantedBy=multi-user.target

其中Description表示服务的简单描述, ExecStart表示需要执行的指令.

修改xxx.service文件权限: sudo chmod 777 xxx.service

开启xxx.service服务: sudo systemctl start xxx.service , 该指令只是临时生效, 重启后服务会停止, 如果想要开机自启动必须要先执行 sudo systemctl enable xxx.service

服务开启后,程序即可执行,就可以看到现象了

服务开机自启动: sudo systemctl enable xxx.service

服务开机不自启动: sudo systemctl disable xxx.service

停止服务: sudo systemctl stop xxx.service 或者 sudo service xxx stop

重启服务: sudo systemctl restart xxx.service 对停止的服务执行此命令和开启服务命令效果一样

查看服务状态: sudo systemctl status xxx.service

查看python3 程序执行的进行: ps -elf|grep python3