Python's argparse to show program's version with prog and version string formatting

PythonVersionArgparse

Python Problem Overview


What's the preferred way of specifying program name and version info within argparse?

version_info = ('2013','03','14')
version = '-'.join(version_info)
...
parser.add_argument('-V', '--version', action='version', version="%(prog)s ("+version+")")

Python Solutions


Solution 1 - Python

Yes, that's the accepted way. From http://docs.python.org/dev/library/argparse.html#action:

>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')

You should of course be embedding the version number in your package in a standard way: https://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package

If you're following that method, you have a __version__ variable:

from _version import __version__
parser.add_argument('--version', action='version',
                    version='%(prog)s {version}'.format(version=__version__))

For example, that's the method demonstrated at https://pypi.python.org/pypi/commando/0.3.2a:

> parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + version)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontypeView Question on Stackoverflow
Solution 1 - PythonecatmurView Answer on Stackoverflow