0

Python's argparse module allows explicit the specification of a version. Unfortunately, it doesn't seem to respect newlines in the output:

import argparse

parser = argparse.ArgumentParser(description="test")

parser.add_argument("--version", "-v", action="version", version="some\ntext")

parser.parse_args()
python3 a.py -v
some text

Any hints on how to work around this?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • If you want a different format, have you tried changing the formatter? https://docs.python.org/3/library/argparse.html#formatter-class – jonrsharpe May 06 '19 at 07:54

2 Answers2

1

Try using the RawTextHelpFormatter:

parser = argparse.ArgumentParser(
    description="test", formatter_class=argparse.RawTextHelpFormatter
)

You should know that this formatter will affect every argument and not just the version.

AdamGold
  • 4,941
  • 4
  • 29
  • 47
1

You could use a custom Action if you want to do something very specific with the version output:

#!/usr/bin/env python

import argparse

class VersionAction(argparse.Action):
    def __init__(self, option_strings, version=None, **kwargs):
        super(VersionAction, self).__init__(option_strings, nargs=0, help="show program's version number and exit", **kwargs)
        self.version = version
    def __call__(self, parser, namespace, values, option_string=None):
        print('%s' % self.version)
        exit(0)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="args")
    parser.add_argument("--version", "-v", action=VersionAction, version="some\ntext")

    parser.parse_args()

Also, this only changes you -v option and does not affect your other options.

laenkeio
  • 502
  • 2
  • 6