Run Python code as a service

Testing of my python script that reads the serial output from MotherHub seems stable enough to run fulltime now. What I’ve found is though that everytime I turn my PC off my SSH session will time out and kill the python script from running. What I need is a way to run it all the time and auto start it after a reboot. Peiter Vanos has just the thing! I am reposting here for my own reference later. You can find the original code at http://www.pietervanos.net

1. place your python script in the following folder: /usr/local/sbin/ (This can be anywhere you like)
2. create a new file in /etc/init.d/ in this case it will be example, so sudo nano /etc/init.d/example
3. Use the following code for the example file

#! /bin/sh
# /etc/init.d/example
 
case "$1" in
start)
echo "Starting example"
# run application you want to start
python /usr/local/sbin/example.py &
;;
stop)
echo "Stopping example"
# kill application you want to stop
killall python
;;
*)
echo "Usage: /etc/init.d/example{start|stop}"
exit 1
;;
esac
 
exit 0

4. give the file execute rights, sudo chmod 755 example
5. now execute: sudo update-rc.d example defaults

When you reboot raspbian it should automatically start the python script, else try service example start and service example stop

 

This worked like a charm for me. I could see SQL entries within a minute! Now to see if it can run 24/7 with no problems

This entry was posted in Linux, Python, Raspberry Pi, SensorNet and tagged , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback.

1 Trackback

  1. […] that count the amount of variables. The next 24 hours will be the big test as I just set the script up as a service for uninterupted SQL insertions I’m sure this script will expand over the coming […]

Leave a Reply