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.

2
  • 1
    unix.stackexchange.com/questions/110698/… might be of help Commented Jun 22, 2016 at 12:40
  • Something simple like pgrep -f 'new_script.py'|| ./new_script.py or you have to use a lockfile with the PID. Commented Jun 22, 2016 at 12:41

2 Answers 2

7

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")
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.