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
  •  | 
  •  

문제

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
도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top