Multiple lines in python argparse help display

后端 未结 3 2210
天涯浪人
天涯浪人 2021-02-13 00:41

I\'m using argparse in Python2.7 and I would like to display multiple lines in the help text of an argument.

My codes look like this:

import argparse

         


        
3条回答
  •  长情又很酷
    2021-02-13 01:06

    The default help formatter re-wraps lines to fit your terminal (it looks at the COLUMNS environment variable to determine the output width, defaulting to 80 characters total).

    From the formatter_class section:

    By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages.

    Use the RawTextHelpFormatter class instead to indicate that you already wrapped the lines:

    RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions.

    For your code that'd look like:

    parser = argparse.ArgumentParser(description='details',
            usage='use "%(prog)s --help" for more information',
            formatter_class=argparse.RawTextHelpFormatter)
    

    Do watch out you don't add too many newlines; triple-quoted strings include the newlines you leave in the string. As such you don't need the \n characters:

    >>> import argparse
    >>> parser = argparse.ArgumentParser(description='details',
    ...         usage='use "%(prog)s --help" for more information',
    ...         formatter_class=argparse.RawTextHelpFormatter)
    >>> parser.add_argument('--argument', default=None,
    ...         help='''
    ...              First line
    ...              Second line
    ... 
    ...              More lines
    ...              ''')
    _StoreAction(option_strings=['--argument'], dest='argument', nargs=None, const=None, default=None, type=None, choices=None, help='\n             First line\n             Second line\n\n             More lines\n             ', metavar=None)
    >>> parser.print_help()
    usage: use " --help" for more information
    
    details
    
    optional arguments:
      -h, --help           show this help message and exit
      --argument ARGUMENT  
                                        First line
                                        Second line
    
                                        More lines
    

提交回复
热议问题