How to run a python script as a service / in background / as a daemon

So you've written a killer python script and you want to run it in the background as a service because when you close the terminal window/SSH session it kills it. I originally worked it out when I wrote my Twitterbot app, and was going to write it up seperately then but it took me so long to get it running in the background and I tried so may things that I couldn't actually tell you how I eventually managed it!

It was only as I was working on my new project - an OLED clock for my new mediacentre pi that I finally worked out how easy it actually was; here are the instructions.

First we'll get the code using a terminal window or SSH:

cd ~
git clone https://github.com/metachris/python-posix-daemon.git
cd python-posix-daemon/scr
ls

so you'll see the three files which do the business:

daemon2x.py
daemon3x.py
daemon-example.py

you'll obviously need python at this point tp do anything so I'll assume you have this, we can try the provided example file to see if everything is working:

python daemon-example.py start

and 

python daemon-example.py stop

to stop it.

At this point you'll notice that nothing really happened - thats because the sample dosen't actually do anything, we can have a look by openeing the file

nano daemon-example.py

it just sleeps for 1 second and then repeats.

If you want to see an example of a script that does something you can use my example:

It creates a log file ant writes the time to it every two seconds. Download the script:

wget https://gist.githubusercontent.com/mc3k/0d0f19d6a92387d2b564cbaec3cdcc54/raw/80a8a462de179dc7a0f359ac1a860a4d2e39b2d0/daemon-example2.py

and start it:

sudo python daemon-exampl2.py start

leave it for and few seconds then stop it:

sudo python daemon-example2.py stop

we can see the results using:

cat /var/log/daemon-example.log

and there you have it, everything is easy when you know how. If you want to put it in you library then you just need to put it in a python sys path.

if you want to run the script at boot you'll need to

sudo nano /etc/rc.local

then type in

echo "Starting python logging daemon"
sudo python /home/pi/python-posix-daemon/scr/daemon-example2.py start

but I wouldn't recommend it for this script.


Search Posts

Back to top