当前位置:   article > 正文

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

树莓派开机自启动

一. 配置rc.local文件方式

编辑/etc/rc.local文件

sudo vi /etc/rc.local

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

  1. #!/bin/sh -e
  2. #
  3. # rc.local
  4. #
  5. # This script is executed at the end of each multiuser runlevel.
  6. # Make sure that the script will "exit 0" on success or any other
  7. # value on error.
  8. #
  9. # In order to enable or disable this script just change the execution
  10. # bits.
  11. #
  12. # By default this script does nothing.
  13. # Print the IP address
  14. _IP=$(hostname -I) || true
  15. if [ "$_IP" ]; then
  16. printf "My IP address is %s\n" "$_IP"
  17. fi
  18. /usr/bin/python3 /home/pi/Desktop/testGPIO.py 23 10 &
  19. exit 0

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

重启系统,就可以生效了

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

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

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

mkdir /home/pi/.config/autostart

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

  1. [Desktop Entry]
  2. Name=controller
  3. Comment=controller Program
  4. Encoding=UTF-8
  5. #Exec=python3 /home/pi/human_code/controller.py
  6. Terminal=false
  7. MultipleArgs=false
  8. Type=Application
  9. Categories=Application;Development;
  10. StartupNotify=true

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

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

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

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

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

文件内容如下:

  1. [Unit]
  2. Description=A server for test
  3. After=network.target
  4. [Service]
  5. Type=simple
  6. Restart=always
  7. RestartSec=5
  8. ExecStart=/usr/bin/python3 /home/pi/Desktop/testGPIO.py 23 10
  9. StandarOutput=null
  10. StandarError=null
  11. [Install]
  12. 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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号