Run python script only if it's not running

末鹿安然 提交于 2021-02-08 04:40: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.


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!