简体   繁体   English

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

[英]Check if second script is running or already finished

I need to check if a scriptA.py is still running, in scriptB.py . 我需要检查,如果一个scriptA.py仍在运行,在scriptB.py Both are started individually, but scriptB.py may only continue if scriptA.py is still running. 两者都是单独启动的,但是只有在scriptA.py仍在运行时, scriptB.py才能继续。

I know I could use 我知道我可以用

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"

But script a runs in a tmux session. 但是脚本a在tmux会话中运行。 Which is called like 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' 这就像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' 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'

If i pgrep scriptA.py it doesn't return the PID . 如果我pgrep scriptA.py不返回PID pgrep tmux would work, but that there might be other tmux sessions, so I can't use that. pgrep tmux可以工作,但是可能还有其他tmux会话,所以我不能使用它。

I could do something like ps aux | grep scriptA.py | wc -l 我可以做类似ps aux | grep scriptA.py | wc -l事情ps aux | grep scriptA.py | wc -l ps aux | grep scriptA.py | wc -l ps aux | grep scriptA.py | wc -l and check the line count - but this feels like it's very variable. ps aux | grep scriptA.py | wc -l并检查行数-但这感觉非常可变。

How else could I verify if scriptA.py is running? 我还能如何验证scriptA.py是否正在运行?

I'm now using the PID , written to a file at script execution.. The code I use seems to work for my case: 我现在正在使用PID ,在执行脚本时将其写入文件。我使用的代码似乎适用于我的情况:

In scriptA , at execution start: scriptA ,在执行开始时:

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

In scriptB , at the beginning of the loop that needs to be executed until scriptA is done. 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM