質問

I'm doing Ussd command to a GSM network. Sometimes the command fails because of unknown details.

I would like to do the following:

If the command issued to the GSM network fail I will wait 4 seconds, If fail again I will wait another 6 seconds. If fail again I will quit and return something like "unknown GSM Operator Error"

My question here is how to handle this loop in Python with a try/except:

This is the code without try/except:

def getGsmCode()
    code = somecommand('xyz')
    return code[0]

I tried to implement this but it is ugly. This is best way of doing it?

def getGsmCode()
    try:
        code = somecommand('xyz')
        return code[0]
    except:
        pass
        # I will try againg after wait 4 seconds
        time.sleep(4)
        try:
            code = somecommand('xyz')
            return code[0]
        except:
            pass
            # I will try again after wait 6 seconds
            time.sleep(6)
            try:
                code = somecommand('xyz')
                return code[0]
            except:
                pass
                return "unknown GSM Operator Error"

Best Regards,

役に立ちましたか?

解決

I would use for loop.

For example:

import time

def somecommand(arg):
    1 / 0

def getGsmCode():
    delays = 4, 6,
    for delay in delays:
        try:
            return somecommand('xyz')[0]
        except:
            #print('sleep {}'.format(delay))
            time.sleep(delay)
    return "unknown GSM Operator Error"

print(getGsmCode())
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top