最近有个项目利用树莓派来完成,主要是在树莓派上用python写了个脚本来处理一些信息与逻辑。这边就遇到一个问题,即设置该脚本在开机的时候自动运行,而不是需要人登陆到树莓派上在执行这个程序,这样太麻烦了,顶多在实验室玩玩,拿不出去。本文主要讲诉设置该python脚本在树莓派上自动运行。
   一、首先写个简单的python 脚本
脚本很简单,就是树莓派上一个灯闪烁程序,需要学gpio可以看我之前的博客
文件保存在/home/pi/script/ledblink.py
| 1						 2						 3						 4						 5						 6						 7						 8						 9						 10						 11						 12						 13						 14						 15						 | #!/usr/bin/env python							 importRPi.GPIO as GPIO							 importtime							 GPIO.setmode(GPIO.BCM)							 GPIO.setup(21,GPIO.OUT)							 whileTrue:							   try:							    GPIO.output(21,True)							    time.sleep(1)							    GPIO.output(21,False)							    time.sleep(1)							   except(KeyboardInterrupt, SystemExit):							    GPIO.close()							    print"exit"							 | 
二 开机启动脚本
保存脚本为/etc/init.d/ledblink文件
| 1						 2						 3						 4						 5						 6						 7						 8						 9						 10						 11						 12						 13						 14						 15						 16						 17						 18						 19						 20						 21						 22						 23						 24						 25						 26						 27						 28						 29						 | #!/bin/bash							 # /etc/init.d/ledblink							 ### BEGIN INIT INFO							 # Provides: embbnux							 # Required-Start: $remote_fs $syslog							 # Required-Stop: $remote_fs $syslog							 # Default-Start: 2 3 4 5							 # Default-Stop: 0 1 6							 # Short-Description: ledblink initscript							 # Description: This service is used to manage a led							 ### END INIT INFO							 case"$1"in							    start)							        echo"Starting LED Blink"							        /home/pi/script/ledblink.py &							        ;;							    stop)							        echo"Stopping ledblink"							        #killall ledblink.py							        kill$(psaux |grep-m 1'python /home/pi/script/ledblink.py'|awk'{ print $2 }')							        ;;							    *)							        echo"Usage: service ledblink start|stop"							        exit1							        ;;							 esac							 exit0							 | 
三 设置python脚本开机启动
| 1						 | sudochmod+x/etc/init.d/ledblink							 | 
这样启动改脚本用service 命令就可以
| 1						 2						 | sudoservice ledblink start#启动							 sudoservice ledblink stop#停止							 | 
最后设置开机启动就好了
| 1						 | sudoupdate-rc.d ledblink defaults							 | 
这样就完工了,重启树莓派就会发现led自己闪烁了,停止用sudo service ledblink stop就行
参考: Run a script on start up
转自:https://www.embbnux.com/2015/04/12/raspberry_pi_setting_python_script_start_on_boot/
 
  
         
         
           
          