python argparse 如何在[-h] 命令后继续执行程序?

python argparse how to continue the program after the [-h] command?

我正在使用 argparse 编写解释器。面临一个问题。

while True:
    cmd = input('>>>')
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', help='foo')
    parser.parse_args(cmd.split())

当我输入 [-h] 命令时,程序退出。

>>>-h
usage: test.py [-h] [-f F]

optional arguments:
-h, --help  show this help message and exit
-f F        foo

现在,我只想要 'show this help message' 而不是 'exit'。请问我该怎么办?

这可以通过删除预定义的帮助命令并添加自己的帮助命令来完成:

import argparse

while True:
    cmd = input('>>>')
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('-h', '--help', action='store_true',
            help = 'show this help message')
    parser.add_argument('-f', help='foo')
    args = parser.parse_args(cmd.split())
    if args.help:
        parser.print_help()