Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rerun code block in Python

I was looking to try to figure out a way to write something like this:

code_that_should_not_be_run_again()
with rerun_code_that_may_fail():
  another_method(x)
  run_me_again_if_i_fail(y)
code_that_should_only_be_run_if_above_succeeds()

Where the above would run that code, and catch an exception, if it was caught, then try to run the code, again. here would be a longer version of what I want:

code_that_should_not_be_run_again()
try:
  another_method(x)
  run_me_again_if_i_fail(y)
catch Exception:
  try:
    another_method(x)
    run_me_again_if_i_fail(y)
  catch Exception:
    raise Exception("Couldn't run")
 code_that_should_only_be_run_if_above_succeeds()

I was thinking I could probably use a generator, maybe catch that yielded content in to a lambda and then run it twice, somehow, but now sure how I can code something like this.

Is this possible in Python? Or maybe something similar to this that can be done?

Here's what I've tried so far:

from contextlib import contextmanager
@contextmanager
def run_code():
    print 'will run'
    try:
      yield
    except SomeException:
      try:
        yield
      except SomeException:
        raise SomeException('couldn't run')

Edit Python wont' let you do what I want to do, so you can only use decorators on functions :(

like image 618
Allen Avatar asked Oct 18 '22 02:10

Allen


1 Answers

Using the retry decorator - https://pypi.python.org/pypi/retry/ - and under the scenario that you want to catch any TypeError, with a maximum of 3 tries, with a delay of 5 seconds:

from retry import retry

@retry(TypeError, tries=3, delay=5)
def code_block_that_may_fail():
    method_1()
    method_2()
    #Some more methods here...

code_block_that_may_fail()

Can't get too much cleaner than that.

Additionally, you can use the built-in logger to log failed attempts (see documentation).

like image 113
Andrew Guy Avatar answered Oct 21 '22 02:10

Andrew Guy