9

I want to construct a argparser help message that looks like:

-i, --input=INPUT    help for input
-o, --output=output  help for output

My current code:

arg_parser = argparse.ArgumentParser
arg_parser.add_argument('-i', '--input', dest='input', metavar='=INPUT', help='help for input')
arg_parser.add_argument('-o', '--output', dest='output', metavar='=OUTPUT', help='help for output')
arg_parser.print_help()

is giving me

-i =INPUT, --input =INPUT    help for input
-o =INPUT, --output =output  help for output

I just want to know how to get rid of the things in between short and long options.

1
  • 2
    There is no way to do this using the default help formatters; you'd have to write a customer help formatter to accomplish this.
    – chepner
    Commented May 29, 2014 at 15:13

3 Answers 3

8

Don't show long options twice in print_help() from argparse

asks essentially the same thing. If you are not up to writing your own HelpFormatter subclass (it probably needs to change one method), you need to play with the existing formatting tools - help, metavar, and description.

Here also argparse help without duplicate ALLCAPS

and How do I avoid the capital placeholders in python's argparse module?

For that 88275023 question I worked out (but didn't post) this Formatter class. The change is near the end

class CustomFormatter(argparse.HelpFormatter):
    def _format_action_invocation(self, action):
        if not action.option_strings:
            metavar, = self._metavar_formatter(action, action.dest)(1)
            return metavar
        else:
            parts = []
            # if the Optional doesn't take a value, format is:
            #    -s, --long
            if action.nargs == 0:
                parts.extend(action.option_strings)

            # if the Optional takes a value, format is:
            #    -s ARGS, --long ARGS
            # change to 
            #    -s, --long ARGS
            else:
                default = action.dest.upper()
                args_string = self._format_args(action, default)
                for option_string in action.option_strings:
                    #parts.append('%s %s' % (option_string, args_string))
                    parts.append('%s' % option_string)
                parts[-1] += ' %s'%args_string
            return ', '.join(parts)
1
  • 7
    metavar = ' ' gives -i , --input (not the whitespace), while metavar = '\b ' gives -i, --input Commented Feb 8, 2020 at 14:15
8

As mentioned in a comment of the accepted answer, following parameter was enough for me.

metavar='\b'
1
  • 1
    I recommend using this if the argument option in question is going to be required=True - if you use metavar='', you'll get an AssertionError.
    – skwidbreth
    Commented Sep 11, 2020 at 14:11
0

Shorter custom formatter version:

import argparse


class HelpFormatter(argparse.HelpFormatter):
    def _format_action_invocation(self, action: argparse.Action) -> str:
        formatted = super()._format_action_invocation(action)
        if action.option_strings and action.nargs != 0:
            formatted = formatted.replace(
                f" {self._format_args(action, self._get_default_metavar_for_optional(action))}",
                "",
                len(action.option_strings) - 1,
            )

        return formatted

Example output:

app@01d3adfb794b:/usr/local/src/app$ app database --help
Usage: app database [-h] [-s] [-d] [-b [NAME]]

Options:
  -h, --help           Show this help message and exit
  -s, --sync           Manually sync the database with the services
  -d, --dump           Dump the database as JSON to the STDOUT
  -b, --backup [NAME]  Generate and store a database backup (default: %timestamp%.bak)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.