6

I want to re-run subprocess.call if it's timeout somehow.

subprocess.call('some command', timeout=600)
if timeout:
    subprocess.call('some command')

How do i do something like this?

2
  • why would you try to call it again immediately if it just timed-out?
    – Ma0
    Commented Jan 21, 2019 at 12:19
  • @Ev.Kounis I had this need too, when I need to contact a service which could take a few minutes to start up. Today i would have done it a bit differently - use a shorter timeout and add Delay before the next attempt
    – yossiz74
    Commented Nov 6, 2019 at 9:58

2 Answers 2

7

subprocess.call raises [Python 3.Docs]: exception subprocess.TimeoutExpired when timeout is (given and) reached (just like Popen.communicate).

Here's a piece of code that keeps launching NotePad with a timeout of 3 seconds, until it runs 2 times, or user manually closes it:

>>> max_runs = 2
>>> run = 0
>>> while run < max_runs:
...     try:
...             subprocess.call("notepad", timeout=3)
...     except subprocess.TimeoutExpired:
...             continue
...     else:
...             break
...     finally:
...             run += 1
...
0

Although this technically answers the question, I don't think it's a good idea to re-launch a process that didn't end, since there's a great chance that the consecutive runs will have the same outcome (will timeout). In that case, you'd have to use Popen and communicate, and if the process times out, kill it via Popen.terminate.

1

You can use basic error handling to do catch the timeout exception:

try:
    subprocess.call('cmd', timeout=0)
except subprocess.TimeoutExpired:
    print('Expired!')
    # subprocess.call('cmd')

The except block is only run if the specified error is raised. See Python docs tutorial on exceptions, specifically error handling for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.