Search code examples
pythonlinuxterminaloptparseoptionparser

How to string format OptionParser() help message?


How to string format OptionParser() help message? It seems to ignore the new line character? Please see below code.

parser = OptionParser()
parser.add_option("--s", dest="s", type="string", help="first line \n second line")

Intention:

current output:
.... first line \n second line

expected output:
.... first line 
     second line

Solution

  • Might I suggest argparse?

    I'm not sure if this is supported in OptionParser, but I would suggest using a triple quote
    i.e:

    parser = OptionParser()
    parser.add_option('--s',
                      dest='s'
                      type='string'
                      help='''
    With triple quotes I can directly put in anything including line spaces.
    \n will appear as a string rather than a newline.''')
    

    argparse example:

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--s',
                      help='''first line
    second line''')
    args = parser.parse_args()
    print args.s