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
cd python-posix-daemon/scr

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

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 start


python 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


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:


and start it:

sudo python start

leave it for and few seconds then stop it:

sudo python 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/ start

but I wouldn't recommend it for this script.

Share page

Subscribe to newsletter

Search Posts

Back to top