Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve newlines in argparse version output while letting argparse auto-format/wrap the remaining help message?

I wrote the following code.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-v', '--version', action='version',
                    version='%(prog)s 1.0\nCopyright (c) 2016 Lone Learner')
parser.parse_args()

This produces the following output.

$ python foo.py --version
foo.py 1.0 Copyright (c) 2016 Lone Learner

You can see that the newline is lost. I wanted the copyright notice to appear on the next line.

How can I preserve the new lines in the version output message?

I still want argparse to compute how the output of python foo.py -h should be laid out with all the auto-wrapping it does. But I want the version output to be a multiline output with the newlines intact.

like image 927
Lone Learner Avatar asked Mar 08 '16 02:03

Lone Learner


2 Answers

RawTextHelpFormatter will turn off the automatic wrapping, allowing your explicit \n to appear. But it will affect all the help lines. There's no way of picking and choosing. Either accept the default wrapping, or put explicit newlines in all of your help lines.

You are getting to a level of pickiness about the help format that you need to study the HelpFormatter code for yourself.

like image 103
hpaulj Avatar answered Sep 25 '22 08:09

hpaulj


There's also argparse.RawDescriptionHelpFormatter.

parser=argparse.ArgumentParser(add_help=True,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""an
already-wrapped
description
string""")

It leaves the description and epilog alone, and wraps only argument help strings. The OP wanted the opposite.

like image 27
Jim Avatar answered Sep 22 '22 08:09

Jim