Reputation: 23
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.
Upvotes: 2
Views: 4281
Reputation: 744
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.
Upvotes: 3
Reputation: 367
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")
Upvotes: 7