如何避免在帮助消息 (-h, --help) 中打印默认值 (argparse)

How to avoid printing the default values (argparse) in the help message (-h, --help)

这是代码。

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="infomedia"
    )
    parser.add_argument("file", help="path to file")

    parser.add_argument(
        "-i",
        "--info",
        type=str,
        default="False",
        help="get information about",
    )

    cli_args = parser.parse_args()

    worker = Worker(
        cli_args.input,
        cli_args.info,
    )

    worker._application()

当程序是 运行 -h / --help 时它显示默认值。

positional arguments:
  file                  path to file

optional arguments:
  -h, --help            show this help message and exit
  -i INFO, --info INFO  get information about (default: False)

如何避免打印默认值?或者有没有办法以不同的方式定义此代码的默认值?

您可以创建继承自 argparse.ArgumentDefaultsHelpFormatter 的新 class 并覆盖 _get_help_string 方法并传递您新创建的 class,在下面的示例中为 MyHelpFormatter作为 ArgumentParser 构造函数中的 formatter_class。这是可以帮助您的示例代码:

import argparse

class MyHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
    def _get_help_string(self, action):
        return action.help

def main():
    parser = argparse.ArgumentParser(
        formatter_class=MyHelpFormatter,
        description="infomedia",
    )
    parser.add_argument("file", help="path to file")

    parser.add_argument(
        "-i",
        "--info",
        type=str,
        default="False",
        help="get information about",
    )

    cli_args = parser.parse_args()

if __name__ == "__main__":
    main()

我想你更想要:

parser.add_argument("--info", help="get information", action="store_true")