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

问题描述 投票:0回答:3

这是代码。

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)

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

python-3.x command-line-arguments argparse
3个回答
2
投票

您可以创建继承自

argparse.ArgumentDefaultsHelpFormatter
的新类并覆盖
_get_help_string
方法,并将新创建的类(以下示例中的
MyHelpFormatter
)传递为
formatter_class
构造函数中的
ArgumentParser
。这是可以帮助您的示例代码:

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()

0
投票

我想你想要更多:

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

0
投票

您可以使用

default=argparse.SUPPRESS
来禁止显示默认值。

© www.soinside.com 2019 - 2024. All rights reserved.