Python的argparse用prog和版本字符串格式显示程序的版本

typ*_*ype 34 python version argparse

在argparse中指定程序名称和版本信息的首选方法是什么?

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

eca*_*mur 64

是的,这是公认的方式.来自http://docs.python.org/dev/library/argparse.html#action:

>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
Run Code Online (Sandbox Code Playgroud)

您当然应该以标准方式将版本号嵌入到包中:将版本嵌入到python包中的标准方法是什么?

如果您正在使用该方法,则您有一个__version__变量:

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

例如,这是在https://pypi.python.org/pypi/commando/0.3.2a上演示的方法:

parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)
Run Code Online (Sandbox Code Playgroud)

  • 如果这是一场圣战,那么在新版本中你甚至可以使用 f-string :D version=f'%(prog)s {__version__}' (3认同)
  • @type`%(var)`是旧`%`字符串格式; `{var}`是新的`format`字符串格式. (2认同)

wig*_*ing 5

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'))
Run Code Online (Sandbox Code Playgroud)

  • `importlib.metadata` 自 3.8 起可用,当时包是在标准库中创建的 (2认同)