简体   繁体   中英

commands execution in python script

I have a python script with a command to be executed like for example:

sample_command_that_may_fail()

Assuming that the above command fails due to network issues and if it succeeds only after 2-3 times executing the command.

is there any built in function in python for retrying it or any links or hints available?I am very much novice in python, as any links to this would be of help to me.

You may consider retrying module.

Example:

import random
from retrying import retry

@retry
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        raise IOError("Broken sauce, everything is hosed!!!111one")
    else:
        return "Awesome sauce!"

print do_something_unreliable()

Since you didn't give any specifics, it's hard to be more, well, specific, but typically you can just use a for loop. An example might look like:

out = None

# Try 3 times
for i in range(3):
    try:
       out = my_command()
    # Catch this specific error, and do nothing (maybe you can also sleep for a few seconds here)
    except NetworkError:
       pass
    # my_command() didn't raise an error, break out of the loop
    else:
        break

# If it failed 3 times, out will still be None
if out is None:
    raise Exception('my_command() failed')

This tries my_command() 3 times. It makes some assumptions about the behaviour of my_command() :

  • It raises a NetworkError on a network error; take care to avoid pokemon exceptions .
  • It returns something other than None on success.

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