问题
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.
回答1:
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")
回答2:
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.
来源:https://stackoverflow.com/questions/37968080/run-python-script-only-if-its-not-running