Skip to content
Advertisement

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement