62

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__+")")
type
  • 1,137
  • 2
  • 9
  • 16

2 Answers2

110

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: 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__)
Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • how would this look like, in a standard way? i see you put your version example of "2.0" verbatim in the argparse code line ... – type Mar 14 '13 at 10:32
  • Fine, after the edit it is answering the question. Thanks a lot. Still I'm confused about %(var) and {var) though ... – type Mar 14 '13 at 12:08
  • 4
    @type `%(var)` is old `%` string formatting; `{var}` is new `format` string formatting. – ecatmur Mar 14 '13 at 12:13
  • 1
    It seems one cannot use a unified string formatting here `parser.add_argument('-V', '--version', action='version', version="{prog}s ({version})".format(prog="%(prog)", version=__version__))` – type Mar 14 '13 at 12:21
  • 3
    if here is a holy war then in new version you can even use f-string :D version=f'%(prog)s {__version__}' – Beliaev Maksim Aug 17 '20 at 16:13
4

Just wanted to post another approach. As of Python 3.11, you can get a package's version number as a string using importlib.metadata. So if your program is a package with a pyproject.toml file then you can get the version number that is defined in that file. The example below get's the version string of a command line tool named genja; where genja is the name of the Python package that is the command line program.

from importlib.metadata import version

parser.add_argument('-v', '--version', action='version', version=version('genja'))
wigging
  • 8,492
  • 12
  • 75
  • 117