2

I want to launch a python script from another python script. I know how to do it. But I should launch this script only if it is not running already.

code:

import os
os.system("new_script.py")

But I'm not sure how to check if this script is already running or not.

learning_prog
  • 23
  • 1
  • 3
  • 1
    http://unix.stackexchange.com/questions/110698/how-to-check-which-specific-processes-python-scripts-are-running might be of help – Jeremy Jun 22 '16 at 12:40
  • Something simple like `pgrep -f 'new_script.py'|| ./new_script.py` or you have to use a lockfile with the PID. – Klaus D. Jun 22 '16 at 12:41

2 Answers2

6

Try this:

import subprocess
import os 

p = subprocess.Popen(['pgrep', '-f', 'your_script.py'], stdout=subprocess.PIPE)
out, err = p.communicate()

if len(out.strip()) == 0:
    os.system("new_script.py")
talhasch
  • 357
  • 4
  • 6
3

Came across this old question looking for solution myself.

Use psutil:

import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'your_script.py']:
        sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'your_script.py'])

You can also use start time of the previous process to determine if it's running too long and might be hung:

process.create_time()

There is tons of other useful metadata of the process.

NST
  • 724
  • 9
  • 20