简体   繁体   中英

Try-except error in Python

I have a Python script which has a batch command in between,

batch_cmd = "batch command"
subprocess.call(batch_cmd)

Consider this scenario where I want to repeat running this batch command if it fails. I tried to use try/except in such a way that the batch_cmd has to be repeated in the 'except' part too. That is:

try: 
    batch_cmd = "batch command"
    subprocess.call(batch_cmd)

except:
    print "error. retrying"
    subprocess.call(batch_cmd)

The exception is not getting caught, however. If the batch command in the try block fails, then it just bypasses the 'except' block and executes the remaining of the script. How can I rewrite the try/except part for this? Or is there any other method other than try/except? I know there have been similar questions on SO but the solutions have not helped me so far.

If you want an exception in case the called command fails (nonzero exit code), use subprocess.check_call(batch_cmd) to execute it.

Also use except subprocess.CalledProcessError: in this case to avoid catching more exceptions than necessary.

I wouldn't recommend it. If anything you should rather set a fixed numbers of re-tries and use a counter to break the loop if it tries too many times. And in case it still fails to execute you raise a new exception to prevent the code from continuing.

If you really need to you could do something recursive like this.

def ExectuteBatchCommand(batch_cmd)
    try: 
        subprocess.call(batch_cmd)
    except subprocess.CalledProcessError:
        print "error. retrying"
        ExectuteBatchCommand(batch_cmd)

subprocess.call returns the error code. Place that in a variable and use an if statement to check if it failed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM