My main python functions accepts argv and calls two other functions with these arguments to set up the whole application.
The issue is that if argv includes -h (`–help) then it is passed to the first function, it prints it’s usage message (generated by argparse) as expected, like below:
optional arguments:
-h, --help show this help message and exit
-x section
but then execution is stopped!, and we are back at the prompt.
I would like the execution to continue so the second function is also called, and its usage message also gets printed. Does anyone know how this can be achieved?
You need to catch the
SystemExitexception:Note that I store the system exit exception raised in
function1; it could be that it was raised as a result of a different action, not the-hflag. Iffunction2doesn’t raise an exception itself, we re-raise the originalSystemExitexception to clean up properly.The
except SystemExit as e:statement captures the exception in a local variablee. The local variable thus assigned is normally deleted at the end of theexceptblock (to prevent a reference cycle); if you want to use that exception outside of theexceptsuite you need to store it in a new variable; this is whyexitedis a separate variable defined outside of theexceptsuite.Alternatively, you can opt to remove the
-hswitch from thefunction1argparser altogether by using theadd_help=Falseoption, then handling help manually there.