pyinvoke / invoke

Pythonic task management & command execution.
http://pyinvoke.org
BSD 2-Clause "Simplified" License
4.31k stars 365 forks source link

Running post tasks even if the main task fail #980

Open mscansian opened 6 months ago

mscansian commented 6 months ago

Hello. I was wondering if there's a way to make sure that a post task runs even if the main task fails with an unhandled exception? Here's a simplified version of my code to illustrate the issue:

@task()
def my_pre_task(ctx):
    # Do some resource provisioning needed by the task

@task()
def my_post_task(ctx):
    # Perform resource cleanup
    # This should always run, but it won't if the main task fails with an unhandled exception

@task(pre=[my_pre_task], post=[my_post_task])
def main_task(ctx):
    # Do something that could also result in an unhandled exception

I know that I can wrap the main_task in a try/finally, but I'd rather not do this if I can find a more elegant solution. I was hoping there was something like post_run_on_failure=True that I could use, or a finally task that behaves like a post but always run.