![](/img/trans.png)
[英]What's a good pip/setuptools compliant version number for a fork of a package?
[英]Get pip/setuptools version of package from within the package?
我有一个使用setuptools
的软件包进行部署。 我希望在程序包(CLI工具)中有一个函数来报告程序包的版本。 这应该报告调用setup
使用的version
字段。 有没有办法可以在已安装的软件包上访问此值?
例如,我的setup.py
调用setup
与version = '0.1.6'
,也installes一个命令行工具tool
。 我希望调用tool --version
打印版本0.1.6
。
通常的做法是在包的主__init__.py
文件中列出它。 例如,如果你的包名为sample
,并且存在于sample
目录中,那么你将得到一个sample/__init__.py
文件,其中包含以下内容:
__version__ = '0.1.6'
def version():
return __version__
然后在CLI界面中使用它。
在你的setup.py
,如果你希望你可以从代码中读取这个值,以便不创建冗余,就像这样:
import os.path
here = os.path.abspath(os.path.dirname(__file__))
# Read the version number from a source file.
# Why read it, and not import?
# see https://groups.google.com/d/topic/pypa-dev/0PkjVpcxTzQ/discussion
def find_version(*file_paths):
# Open in Latin-1 so that we avoid encoding errors.
# Use codecs.open for Python 2 compatibility
with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f:
version_file = f.read()
# The version line must have the form
# __version__ = 'ver'
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name="sample",
version=find_version('sample', '__init__.py'),
# ... etc
有关实现此类目标的不同方法的更多讨论,请查看http://packaging.python.org/en/latest/tutorial.html#version
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.