Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

python argparse help message, disable metavar for short options?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...