Rerun code block in Python
<p>I was looking to try to figure out a way to write something like this:</p>

<pre><code>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()
</code></pre>

<p>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:</p>

<pre><code>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()
</code></pre>

<p>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.</p>

<p>Is this possible in Python? Or maybe something similar to this that can be done?</p>

<p>Here's what I've tried so far:</p>

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

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