Search code examples
python-3.xcommand-line-argumentsargparse

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


Here is the code.

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

When the program is running with -h / --help it shows the default values.

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)

How to avoid printing the default values? Or is there a way to define the default values of this code in a different way?


Solution

  • You can create new class inheriting from argparse.ArgumentDefaultsHelpFormatter and override _get_help_string method and pass your newly created class which is MyHelpFormatter in the below example as formatter_class in ArgumentParser constructor. Here is the example code which can help you:

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