Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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__+")") 
  • http://argparse.googlecode.com/svn/trunk/doc/ArgumentParser.html#prog
  • http://pymotw.com/2/argparse/
  • http://www.python.org/dev/peps/pep-0386/
  • http://www.python.org/dev/peps/pep-0396/
  • http://www.python.org/dev/peps/pep-3001/
like image 480
type Avatar asked Mar 14 '13 09:03

type


People also ask

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.

What does parse_args return?

Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

What is Argparse ArgumentParser ()?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.


1 Answers

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__) 
like image 183
ecatmur Avatar answered Sep 25 '22 00:09

ecatmur