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

Ganesh Pal ganesh1pal at gmail.com
Fri Mar 16 01:34:22 EDT 2018


 import time

from functools import wraps

from qa.utils.easy_popen import run





def retry(ExceptionToCheck, tries=4, delay=5, backoff=2, logger=None):

    """ Retry calling the decorated function """

    def deco_retry(f):

        @wraps(f)

        def f_retry(*args, **kwargs):

            mtries, mdelay = tries, delay

            while mtries > 1:

                try:

                    return f(*args, **kwargs)

                except ExceptionToCheck, e:

                    msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)

                    if logger:

                        logger.warning(msg)

                    else:

                        print msg

                    time.sleep(mdelay)

                    mtries -= 1

                    mdelay *= backoff

            return f(*args, **kwargs)



        return f_retry  # true decorator



    return deco_retry







@retry(Exception, tries=4, delay=2)

def test_network(text):

    try:

         cmd = "ifconfig -a"

        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 Exception as e:

           print str(e)

           raise Exception("Failed")

    print "Success: ", text



test_network("it works!")





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



Case 1:  + ve case ( say cmd= ifconfig –a )



gpal-zkj2wrc-1# python  file5.py

vmx0: flags=1008843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST,ISIINTERNAL>
metric 0 mtu 1500


options=403bb<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,JUMBO_MTU,VLAN_HWCSUM,TSO4,TSO6,VLAN_HWTSO>

        ether 00:50:56:90:ef:3d

        inet 1.224.39.1 netmask 0xffff0000 broadcast 1.224.255.255 zone 1

        inet6 fe80::250:56ff:fe90:ef3d%vmx0 prefixlen 64 scopeid 0x1 zone 1

        inet6 fdfe:9042:c53d:0:250:56ff:fe90:ef3d prefixlen 64 zone 1

        nd6 options=21<PERFORMNUD,AUTO_LINKLOCAL>

        media: Ethernet 10Gbase-T

        status: active

vmx1: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500


options=403bb<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,JUMBO_MTU,VLAN_HWCSUM,TSO4,TSO6,VLAN_HWTSO>

        ether 00:50:56:90:62:44

        inet 10.224.39.1 netmask 0xfffffc00 broadcast 10.224.39.255 zone 1

        nd6 options=29<PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL>

        media: Ethernet 10Gbase-T

        status: active



Case 1 : Say I have invalid input  command ( say ifconfig –a ) it will work



gpal-zkj2wrc-1# python  file5.py

 ifconfig: illegal option -- z

usage: ifconfig [-f type:format] [-L] [-C] [-g groupname] interface
address_family

                [address [dest_address]] [parameters]

       ifconfig interface create

       ifconfig -a [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]
[address_family]

       ifconfig -l [-d] [-u] [address_family]

       ifconfig [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]

1

ERROR (exit_code 1):

stdout:

stderr: ifconfig: illegal option -- z

usage: ifconfig [-f type:format] [-L] [-C] [-g groupname] interface
address_family

                [address [dest_address]] [parameters]

       ifconfig interface create

       ifconfig -a [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]
[address_family]

       ifconfig -l [-d] [-u] [address_family]

       ifconfig [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]





Failed, Retrying in 2 seconds...

 ifconfig: illegal option -- z

usage: ifconfig [-f type:format] [-L] [-C] [-g groupname] interface
address_family

                [address [dest_address]] [parameters]

       ifconfig interface create

       ifconfig -a [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]
[address_family]

       ifconfig -l [-d] [-u] [address_family]

       ifconfig [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]

1

ERROR (exit_code 1):

stdout:

stderr: ifconfig: illegal option -- z

usage: ifconfig [-f type:format] [-L] [-C] [-g groupname] interface
address_family

                [address [dest_address]] [parameters]

       ifconfig interface create

       ifconfig -a [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]
[address_family]

       ifconfig -l [-d] [-u] [address_family]

       ifconfig [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]





Failed, Retrying in 4 seconds...



Case 3:  Assuming my command  threw  an exception say OSError , how do I
retry a command only for a specific exception / error



I am on Python 2.7 and Linux




Regards,
Ganesh Pal



More information about the Python-list mailing list