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

本文介绍如何在 Raspberry Pi 上设置 Python 脚本开机自启动,包括创建运行脚本、设置权限及配置 rc.local。通过在 root 账户下编辑 rc.local 文件,实现 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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值