简体   繁体   中英

How to let linux(raspberry) run python script when plugin power?

I have a python script( namely /home/pi/x.py ). And I have tried a lot of ways to let the program, some thing such as:

#!/bin/bash
# /etc/init.d/mystart  
### BEGIN INIT INFO
# Provides: Python 

(I am thinking am I right here(Provides: Python)?)

# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: my python initscript
# Description: no description
### END INIT INFO   case "$1" in
    start)
        echo "Starting x.py "
        /home/pi/x.py &
        ;;
    stop)
        echo "Stopping x.py"
        #killall x.py
        kill $(ps aux | grep -m 1 'python /home/pi/x.py' | awk '{ print $2 }')
        ;;
    *)
        echo "Usage: service x.py start|stop"
        exit 1
        ;; esac exit 0

I have modified this bash from its original form, and put it in

/etc/inti.d/mystart

sudo chmod +x /etc/init.d/mystart

sudo update-rc.d mystart defaults

However, when I try to: sudo service mystart start

Some error comes out! [Unit mystart.service failed to load: No such file or directory.]

So I'm blocked here, I dont know how to let x.py run while it the power is on

Open /etc/profile

sudo nano /etc/profile

Scroll to the bottom and add the following line :

sudo python /home/pi/x.py

where “/home/pi/x.py” is the absolute path to your script. Type “Ctrl+X” to exit, then “Y” to save followed by “Enter” twice. Now reboot and test. python script should now run on startup

Auto Login Setup(to execute script without any intervention from user)

  • Open /etc/inittab

    sudo nano /etc/inittab

  • Find this line

    1:2345:respawn:/sbin/getty 115200 tty1

  • Add a # character to the beginning of the line to disable it so it looks like

    #1:2345:respawn:/sbin/getty 115200 tty1

  • Under that line, add the following:

    1:2345:respawn:/bin/login -f pi tty1 /dev/tty1 2>&1

where “pi” is the username. Type “Ctrl+X” to exit, then “Y” to save followed by “Enter” twice. Now on startup, raspberrypi will autologin with pi user and execute your script

What if you don't have /etc/inittab?

I assume you're using the latest Raspian-Image (jessie). This one is based on Debian 8 (jessie) where the init-system changed. Autologin solution is already mentioned here

Source: http://www.raspberrypi-spy.co.uk/2015/02/how-to-autorun-a-python-script-on-raspberry-pi-boot/

I used crontab and it works well

Step 1:

sudo crontab -e

Step 2: fill in it

@reboot python /home/pi/x.py &

Step 3: Save it and reboot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM