一. 配置rc.local文件方式
編輯/etc/rc.local文件
sudo vi /etc/rc.local
在文件中exit 0 之前添加需要執(zhí)行的命令,文件路徑使用絕對路徑,如:
#!/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
注意:如果程序是阻塞的,則必須加上&符號,表示在后臺運行,否則系統(tǒng)無法啟動
重啟系統(tǒng),就可以生效了
二. 新建desktop文件設(shè)置樹莓派開機啟動項
這種方式類似Windows系統(tǒng)的"開始"菜單中的"啟動"項,操作方法如下:
在/home/pi/.config 文件夾下創(chuàng)建一個文件夾,名稱為autostart
mkdir /home/pi/.config/autostart
在該文件夾下創(chuàng)建一個xxx.desktop文件,文件名以.desktop結(jié)尾,名稱為xxx,可自定義,文件內(nèi)容如下:
[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分別表示啟動文件的名稱,備注,顯示圖標(biāo),他們的值可以自己設(shè)定;
Exec表示調(diào)用的指令,相當(dāng)于在shell終端執(zhí)行的指令.
重啟系統(tǒng),就可以生效了.
三. 以后臺服務(wù)的方式設(shè)置開機啟動程序
創(chuàng)建服務(wù)文件 /etc/systemd/system/xxx.service
文件內(nèi)容如下:
[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表示服務(wù)的簡單描述, ExecStart表示需要執(zhí)行的指令.
修改xxx.service文件權(quán)限: sudo chmod 777 xxx.service
開啟xxx.service服務(wù): sudo systemctl start xxx.service , 該指令只是臨時生效, 重啟后服務(wù)會停止, 如果想要開機自啟動必須要先執(zhí)行?sudo systemctl enable?xxx.service?
服務(wù)開啟后,程序即可執(zhí)行,就可以看到現(xiàn)象了
服務(wù)開機自啟動:?sudo systemctl enable?xxx.service
服務(wù)開機不自啟動:?sudo systemctl disable?xxx.service
停止服務(wù):?sudo systemctl stop xxx.service 或者 sudo service xxx stop
重啟服務(wù):?sudo systemctl restart xxx.service 對停止的服務(wù)執(zhí)行此命令和開啟服務(wù)命令效果一樣
查看服務(wù)狀態(tài):?sudo systemctl status xxx.service文章來源:http://www.zghlxwxcb.cn/news/detail-583720.html
查看python3 程序執(zhí)行的進行: ps -elf|grep python3文章來源地址http://www.zghlxwxcb.cn/news/detail-583720.html
到了這里,關(guān)于樹莓派設(shè)置開機自啟動的三種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!