Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I execute a python script in the background if it is not already running? An example use for this is on the cron.

share|improve this question

if you want a script to start once at startup and theoretically it stays up then you should add it as a service to init.d with the appropriate runlevel set.

Of course if it should go down then you would want to to come back up.

to do that you can have a shell script run ps -aux | grep 'nameOfYourScript' like that. Of course don't include the grep command which will match as well lol. have that script check every five minutes with a cron like this */5 * * * * user

the checkScript you make could be written to start up the program.

share|improve this answer
More generally: there is no foolproof method to check if a program is already running. Search this site with keywords such as daemontools. – reinierpost Oct 12 '10 at 8:12

You could do something like this:


# count the number of processes that match "NameOfProcess" but 
# exclude the grep process itself
pc=`ps -ef |grep "NameOfProcess" |grep -v grep |wc -l`

# if pc > 0, the process is already running and we can exit.
if [ $pc -gt 0 ] ; then
    echo "Application is already running, exiting."
    exit 0

# othewise start the program

Put this in crontab or start with

nohup /path/to/ &

nohup will make sure that the process isnt shutdown if you exit the ssh session. An alternative to this is screen

share|improve this answer
I'd pick nohup over screen myself, but whatever works, works. – pjmorse Oct 12 '10 at 12:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.