Check if second script is running or already finished
Question: I need to check if a `scriptA.py` is still running, in `scriptB.py`. Both are
started individually, but `scriptB.py` may only continue if `scriptA.py` is
still running.

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. 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'`

If i `pgrep scriptA.py` it doesn't return the `PID`. `pgrep tmux` would work,
but that there might be other tmux sessions, so I can't use that.

I could do something like `ps aux | grep scriptA.py | wc -l` and check the line count - but this feels like it's very variable.

How else could I verify if `scriptA.py` is running?


Answer: I'm now using the `PID`, written to a file at script execution.. The code I
use seems to work for my case:

In `scriptA`, at execution start:

    
    
    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.

    
    
    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) 
    

