检查第二个脚本是否正在运行或已完成

时间:2014-12-09 10:03:21

标签: python linux process tmux

我需要在scriptA.py中检查scriptB.py是否仍在运行。两者都是单独启动的,但scriptB.py只有在scriptA.py仍在运行时才会继续。

我知道我可以使用

import subprocess

process = subprocess.Popen(['pgrep', 'scriptA.py'], stdout=subprocess.PIPE)

process.wait()

if not process.returncode:
    print "Process running"
else:
    print "Process not running"

但脚本a在tmux会话中运行。其名称为tmux new -d -s scriptA_2014-12-09-10-54-02-697559 'cd /home/user/scriptA; python scriptA.py -flag; echo $? > /tmp/scriptA_2014-12-09-10-54-02-697559'

如果我pgrep scriptA.py它没有返回PIDpgrep tmux可以使用,但可能还有其他tmux会话,所以我无法使用它。

我可以做ps aux | grep scriptA.py | wc -l之类的事情并查看行数 - 但这感觉它变化很大。

我还能如何验证scriptA.py是否正在运行?

1 个答案:

答案 0 :(得分:0)

我现在正在使用PID,在脚本执行时写入文件..我使用的代码似乎适合我的情况:

scriptA中,执行开始时:

pidf = open("./scriptA_pid.tmp","w")
pidf.write(str(os.getpid()))
pidf.close()

scriptB中,在循环开始时需要执行scriptA

with open("./scriptA_pid.tmp","r") as f:
    scriptA_pid = f.read()
chk_sA = subprocess.Popen(['kill -0 '+str(scriptA_pid)+' > /dev/null 2>&1; echo $?'],stdout=subprocess.PIPE,stderr=devnull,shell=True)
chk_sA.wait()
sA_status = chk_sA.stdout.read()

if int(sA_status) == 0:
    #ScriptA is still running
    pass
else:
    #ScriptA is not running
    sys.exit(0) 
相关问题