如何在我的包中获取 setup.py (setuptools) 中定义的版本? [英] How can I get the version defined in setup.py (setuptools) in my package?

查看:53
本文介绍了如何在我的包中获取 setup.py (setuptools) 中定义的版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从我的包中获取 setup.py 中定义的版本(用于 --version 或其他目的)?

How could I get the version defined in setup.py from my package (for --version, or other purposes)?

推荐答案

查询已安装发行版的版本字符串

要在运行时从包内部检索版本(您的问题似乎实际上是在问什么),您可以使用:

Interrogate version string of already-installed distribution

To retrieve the version from inside your package at runtime (what your question appears to actually be asking), you can use:

import pkg_resources  # part of setuptools
version = pkg_resources.require("MyProject")[0].version

存储版本字符串以供安装期间使用

如果您想反其道而行(这似乎是这里的其他答案作者似乎认为您在问的问题),请将版本字符串放在一个单独的文件中,然后在 setup 中读取该文件的内容.py.

您可以使用 __version__ 行在包中创建 version.py,然后使用 execfile('mypackage/version.py') 从 setup.py 中读取它,以便它在 setup.py 命名空间中设置 __version__.

You could make a version.py in your package with a __version__ line, then read it from setup.py using execfile('mypackage/version.py'), so that it sets __version__ in the setup.py namespace.

如果您想要一种更简单的方法来处理所有 Python 版本,甚至可能需要访问版本字符串的非 Python 语言:

If you want a much simpler way that will work with all Python versions and even non-Python languages that may need access to the version string:

将版本字符串存储为纯文本文件的唯一内容,例如命名为VERSION,并在 setup.py 期间读取该文件.

Store the version string as the sole contents of a plain text file, named e.g. VERSION, and read that file during setup.py.

version_file = open(os.path.join(mypackage_root_dir, 'VERSION'))
version = version_file.read().strip()

相同的 VERSION 文件在任何其他程序中都可以正常工作,甚至是非 Python 程序,您只需要在一个地方为所有程序更改版本字符串.

The same VERSION file will then work exactly as well in any other program, even non-Python ones, and you only need to change the version string in one place for all programs.

顺便说一句,不要按照此处另一个答案中的建议从 setup.py 导入您的包:它似乎对您有用(因为您已经安装了包的依赖项),但它会对新用户造成严重破坏包,因为如果不先手动安装依赖项,他们将无法安装您的包.

By the way, DO NOT import your package from your setup.py as suggested in another answer here: it will seem to work for you (because you already have your package's dependencies installed), but it will wreak havoc upon new users of your package, as they will not be able to install your package without manually installing the dependencies first.

这篇关于如何在我的包中获取 setup.py (setuptools) 中定义的版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆