您需要捕获SystemExit异常:
exited = None
try:
function1(argv)
except SystemExit as e:
# don't exit just yet
exited = e
function2(argv)
# If function 2 *did not* exit, there was a legitimate reason
# re-raise the SystemExit exception
if exited is not None:
raise exited
请注意,我将系统退出异常存储在function1; 它可能是由于不同的动作而不是-h旗帜而引起的。如果function2本身没有引发异常,我们会重新引发原始SystemExit异常以正确清理。
该except SystemExit as e:语句在局部变量中捕获异常e。这样分配的局部变量通常在块的末尾被删除except(以防止引用循环);如果您想在except套件之外使用该异常,则需要将其存储在一个新变量中;这就是为什么在套件exited之外定义一个单独的变量的原因。except
或者,您可以选择使用该选项-h从 argparser 中完全删除开关,然后在此处手动处理帮助。function1add_help=False