how do I retry a command only for a specific exception / error

Ganesh Pal ganesh1pal at gmail.com
Mon Mar 19 12:38:09 EDT 2018


On Fri, Mar 16, 2018 at 11:21 AM, Steven D'Aprano <
steve+comp.lang.python at pearwood.info> wrote:

> On Fri, 16 Mar 2018 11:04:22 +0530, Ganesh Pal wrote:
>
> > All that I  am trying to do here is write a generic function that will
> >  re-retry
> > the command  few more times before failing the test
>
>
> Something like this should do it. It gives up immediately on fatal errors
> and tries again on temporary ones. (You have to specify what you consider
> fatal or temporary, of course.) It uses exponential backup to wait longer
> and longer each time you fail, before eventually giving up.
>
>
> This is a good suggestion ,  I like the way this is written , but what I
> have failed to figure out is how to translate the possible  TemporaryFailureErrors
> to a different exception class/type  and retry .
>
>  In my case ,  every  command is executed using a run() function  that
> calls out to subprocess.Popen().   Which will return  stdout, stderr,
> exit_code and we would need to retry only for a specific
> TemporaryFailureError .
>
>
>
> Example : Say , If we are not able to  SSH  to the host  , and I get
> “connection refused” error I would want to retry only for this specific case
>
>
>
> # Sample modified code
>
>
>
> delay = 2
>
> max_attempts =4
> for attempts in range(max_attempts):
>     try:
>          cmd = "ssh  root at localhost.com"
>
>         stdout, stderr, exit_code = run(cmd, timeout=300)
>
>         print stdout, stderr, exit_code
>
>         if exit_code != 0:
>
>             raise RuntimeError("ERROR (exit_code %d): "
>
>                                "\nstdout: %s\nstderr: %s\n" % (exit_code,
> stdout, stderr))
>
>     except Exeception as e :
>         raise
>
>     # if we have “connection refused” error then retry after some time
>     except TemporaryFailureError:
>         sleep(delay)
>         delay *= 2
>     else:
>         break
> else:
>     raise RuntimeError("too many attempts")
>
>
>
>
Regards,
Ganesh



More information about the Python-list mailing list