I'm using Click to build a Python CLI and am running into an issue with how exceptions are handles in Click.
I'm not sure about the wording ("subcommand", "parentcommand") here but from my example you'll get the idea I hope. Let's assume this code:
@click.group()
@click.option("--something")
def mycli(something):
try:
#do something with "something" and set ctx
ctx.obj = {}
ctx.obj["somevar"] = some_result
except:
print("Something went wrong")
raise
#only if everything went fine call mycommand
@click.group()
@click.pass_context
def mygroup(ctx):
pass
@mygroup.command(name="mycommand")
@click.pass_context
def mycommand(ctx):
#this only works if somevar is set in ctx so don't call this if setting went wrong in mycli
When the application starts this is called:
if __name__ == "__main__":
mycli.add_command(mygroup)
mycli()
I then start the program like this:
python myapp --something somevalue mycommand
Expected behaviour: first mycli
is called and the code in it is executed. If an exception is thrown it's caught by the except block, a message is printed and the exception is raised. Because we have no other try/except block this will result in termination of the script. The "sub"-command mycommand
is never called because the program already terminated when running the "parent"-command mycli
.
Actual behaviour: the exception is caughtand the message is printed, but mycommand
is still called. It then fails with another exception message because the required context variable was not set.
How would I handle something like that? Basically I only want to call the subcommand mycommand
only to be executed if everything in mycli
went fine.
exit()
in the subcommand. – Rubber