Before I run my python script I need to check if an external program is running and wait for it to finish.
I have a few pieces but am having some difficulty putting it all together into a cohesive script.
I can use the following to get the PID of a program and a while loop which will timeout in 10 seconds
from subprocess import check_output
import time
def get_pid(name):
return check_output(["pidof",name])
print "%s" % get_pid("java")
timeout = time.time() + 10
test = 0
while True:
if time.time() > timeout:
print "exception goes here"
break
test = test + 1
time.sleep(1)
If the program is not running get_pid would fail and I think I need to catch the exception in that case? This is where I am not certain where to go. Maybe there is a better way to approach this?
==============
Here is an update which seems to work correctly.
from subprocess import check_output, CalledProcessError
import time
def get_pid(name):
try:
process_status = check_output(["pidof",name])
except CalledProcessError as e:
process_status = None
return process_status
timeout = time.time() + 10
program = "java"
while get_pid(program) != None:
time.sleep(1)
print "1 second loop"
if time.time() > timeout:
raise ValueError ('Timeout exceeded')
print "%s is not running" % program