bc81
bc81

Reputation: 187

python wait using a timeout for an external program to finish

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

Upvotes: 0

Views: 391

Answers (3)

ranjith
ranjith

Reputation: 361

Exception handling can be at the place where the exception is thrown. So if check_output is throwing exception, you could handle below way,

def get_pid(name):
    pid_ = None 
    try:
       pid_ = check_output(["pidof",name])
    except:
       pass
    return pid_
#logic to wait for pid_ to finish if found

Upvotes: 0

Aditya
Aditya

Reputation: 352

You can try catching this exception. Because when check_output returns non zero exception instance of CalledProcessError is raised which can be handled. Like this.

from subprocess import CalledProcessError
def get_pid(name):

    try:
        process_status = check_output(["pidof",name])
    except CalledProcessError as e:
        process_status = None # You can additionally get return code in the returncode attribute and any output in the output attribute.
    return process_status

Hope it works!

Upvotes: 1

Ibaboiii
Ibaboiii

Reputation: 89

Have you tried using the try and except block? E.g.

try:
 #some code
except (RuntimeError, TypeError, NameError):
 #pass etc.

You can read the docs here Handling Exceptions

Upvotes: 0

Related Questions