Linux设置开机自启动Python程序的两种方式(树莓派)

rc.local

  1. 新建运行脚本
pi@zero:~/Documents/Internet $ sudo nano test.sh
#!/bin/sh
cd /home/pi/Documents/Internet
/usr/bin/python3 test.py > test.log &
  1. 赋予脚本可执行权限
pi@zero:~/Documents/Internet $ sudo chmod +x test.sh
  1. root账户下设置开机自启
root@zero:~# nano /etc/rc.local
# 在exit 0 之前添加脚本运行路径
/home/pi/Documents/Internet/./test.sh &

exit 0
  1. 赋予rc.local可执行权限并重启
root@zero:~# sudo chmod +x rc.local
root@zero:~# sudo reboot
  • 如果程序未运行成功,查看运行状态,会有相应的提示
pi@zero:~ $ systemctl status rc-local
Warning: The unit file, source configuration file or drop-ins of rc-local.service changed on disk. Run 'systemctl daemon-reload' to reload units.
● rc-local.service - /etc/rc.local Compatibility
   Loaded: loaded (/lib/systemd/system/rc-local.service; enabled-runtime; vendor preset: enabled)
  Drop-In: /lib/systemd/system/rc-local.service.d
           └─debian.conf
           /etc/systemd/system/rc-local.service.d
           └─ttyoutput.conf
   Active: active (running) since Tue 2019-12-17 19:11:46 CST; 2min 12s ago
     Docs: man:systemd-rc-local-generator(8)
  Process: 354 ExecStart=/etc/rc.local start (code=exited, status=0/SUCCESS)

profile

  1. 新建运行脚本
pi@zero:~/Documents/Internet $ nano test.sh
/usr/bin/python3 /home/pi/Documents/Internet/test.py > /home/pi/Documents/Internet/mylog &
  1. 赋予脚本可执行权限
pi@zero:~/Documents/Internet $ sudo chmod +x test.sh
  1. 设置脚本为开机自启(以下切换到root账户)
pi@zero:~/Documents/Internet $ sudo -i
root@zero:~# nano /etc/profile

在文本结尾添加:

/bin/sh /home/pi/Documents/Internet/test.sh
  • 注意事项
    1.python建议写上绝对路径。
    2.若发现程序无法运行出结果,可能是test.py文件缺少相应的库文件,需要在root账户下下载相应的库文件,比如
 pip3 install <packages-name>

你可能感兴趣的:(树莓派,Linux,Python)