• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
艾苦jvvvdb
帮助1

一. 配置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.  
     
  14.  
    # Print the IP address
  15.  
    _IP=$(hostname -I) || true
  16.  
    if [ "$_IP" ]; then
  17.  
    printf "My IP address is %s\n" "$_IP"
  18.  
    fi
  19.  
     
  20.  
    /usr/bin/python3 /home/pi/Desktop/testGPIO.py 23 10 &
  21.  
     
  22.  
    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.  
     
  5.  
    [Service]
  6.  
    Type=simple
  7.  
    Restart=always
  8.  
    RestartSec=5
  9.  
    ExecStart=/usr/bin/python3 /home/pi/Desktop/testGPIO.py 23 10
  10.  
    StandarOutput=null
  11.  
    StandarError=null
  12.  
     
  13.  
    [Install]
  14.  
    WantedBy=multi-user.target

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

修改xxx.service文件权限: sudo chmod 777 xxx_service.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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhiagaic
系列文章
更多 icon
同类精品
更多 icon
继续加载