树莓派启动时自动运行python程序

小白一枚,记录过程。
参考网址:https://www.instructables.com/id/Raspberry-Pi-Launch-Python-script-on-startup/
题目为:Raspberry Pi: Launch Python Script on Startup

python代码文件名为project1.py,位置为:home/pi/project。打开project 文件夹。

cd project

创建shell脚本。

nano launcher.sh

在nano文本编辑器输入下面代码

cd /
cd home/pi/project
sudo python project1.py
cd /

按ctrl+x 离开,Y保存。

在位置为:home/pi/project,输入下面代码:

chmod 755 launcher.sh

然后,输入下面代码,测试程序:

sh launcher.sh

在pi目录下创建目录存储错误。
输入下面代码,返回pi目录

cd

在位置为:home/pi/,创建目录,代码如下:

 mkdir logs

编辑crontab 文件,代码如下

sudo crontab -e

弹出了下面界面

  GNU nano 2.7.4           檔案: /tmp/crontab.XPXPhz/crontab                    

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

在文档下方输入下面代码

@reboot sh /home/pi/project/launcher.sh >/home/pi/logs/cronlog 2>&1

按ctrl+x 离开,Y保存

重启树莓派,代码如下:

sudo reboot

开机时,成功执行代码。

如果不行,可以查阅log文件,代码如下:

 cd logs
cat cronlog

给树莓派加上电源(充电宝)可以实现可穿戴设备的制作。

另外,如果不想在启动时执行本项目,就编辑crontab文件,将刚刚加上去等最后一行代码删除就可以了。

参考书:《树莓派+传感器:创建智能交互项目的实用方法、工具及最佳实践》作者:[印度] 鲁什·贾加(Rushi Gajjar) Page 71-72

猜你喜欢

转载自blog.csdn.net/weixin_41860080/article/details/87211518