如何将 argparse 与 python 和程序标志一起使用?

How to use argparse with both python and program flags?

python -i prog.py -h

当调用上述命令时,我得到了带有回溯和 'SystemExit: 0' 的预期输出。如果没有“-i”,我会得到没有回溯的预期输出。为什么会发生这种情况,有没有办法在同一个命令中同时使用 python 标志和程序标志而无需回溯?

运行 Python 与 -i 标志改变了 SystemExit 异常的处理,它用于 sys.exit 之类的事情。通常,未捕获的 SystemExit 会导致 Python 静默退出。然而,在 -i 开启的情况下,SystemExit 被视为任何其他异常,带有回溯和所有内容。

如果你想在 -i 开启时关闭 SystemExit 回溯,你需要明确地捕获并忽略它们。例如,

def main():
    try:
        ...
    except SystemExit:
        # Catch the exception to silence the traceback when running under python -i
        pass

if __name__ == '__main__':
    main()

来自docs

exception SystemExit
This exception is raised by the sys.exit() function. When it is not handled, the Python interpreter exits; no stack traceback is printed.

argparse 使用带有“-h”选项的 SystemExit 异常,并且由于您使用命令行参数“-i”进入交互模式,您会看到回溯。请注意,如果您实施并发送不同的选项,回溯是 not 打印的:

python -i prog.py -p 80

两个直接"quick-fixes"我能想到(但实际上,这归结为你真正需要这个做什么?)

  1. 在解析参数时放入 try-except 子句。

  2. python -i prog.py -h 2> /dev/null