树莓派启动时自动运行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文件,将刚刚加上去等最后一行代码删除就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值