Using Python's subprocess module, is there a way to skip an execution when the call gets stuck?

StackOverflow https://stackoverflow.com/questions/23553728

  •  18-07-2023
  •  | 
  •  

Question

As part of a larger program, I am using

a subprocess.call('some external program', shell=True)

(It is an old C program and I only have the compiled version sitting on a network server, so I can't just grab the C source code and interface it with Python)

to temporarily generate some data, which I read into Python again. The problem is that the external program called via subprocess sometimes gets stuck on certain input files. Is there a way to skip the subprocess.call(), e.g., if the shell doesn't respond after some arbitrary time limit?

E.g., 

# for data in directory:
    # do sth.
    subprocess.call('call prog.', shell=True) # skip if takes longer than 5 min
    # analyze data
Was it helpful?

Solution

Starting with Python 3.3 you can set the timeout argument in seconds:

try:
    return_code = subprocess.call('call prog.', shell=True, timeout=10)
except TimeoutExpired:
    # handle timeout exception here which gets throw after
    # 10 seconds in this example
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top