我使用setuptools安装了Python模块construct和statlib:
sudo apt-get install python-setuptools
sudo easy_install statlib
sudo easy_install construct
如何从命令行检查它们的版本?
我使用setuptools安装了Python模块construct和statlib:
sudo apt-get install python-setuptools
sudo easy_install statlib
sudo easy_install construct
如何从命令行检查它们的版本?
当前回答
(请参见如何以编程方式获取Python中已安装模块的版本?)
我发现使用各种可用的工具(包括Jakub Kukul回答中提到的最好的pkg_resources)是非常不可靠的,因为大多数工具都不能覆盖所有情况。例如
内置模块 模块没有安装,只是添加到python路径(例如,通过IDE) 同一模块可用的两个版本(python路径中的一个取代已安装的版本)
因为我们需要一种可靠的方法来获取任何包、模块或子模块的版本,所以我最终编写了getversion。使用起来很简单:
from getversion import get_module_version
import foo
version, details = get_module_version(foo)
详细信息请参见文档。
其他回答
根据Jakub Kukul的回答,我找到了一个更可靠的方法来解决这个问题。
这种方法的主要问题是要求包按“常规”安装(不包括使用pip install——user),或者在Python初始化时位于系统PATH中。
要解决这个问题,可以使用pkg_resources. find_distributors (path_to_search)。如果path_to_search在系统PATH中,它基本上会搜索可导入的分布。
我们可以像这样遍历这个生成器:
avail_modules = {}
distros = pkg_resources.find_distributions(path_to_search)
for d in distros:
avail_modules[d.key] = d.version
这将返回一个以模块为键,其版本为值的字典。这种方法可以扩展到比版本号更多的版本。
感谢Jakub Kukul指出了正确的方向。
你可以试试
>>> import statlib
>>> print statlib.__version__
>>> import construct
>>> print contruct.__version__
这是PEP 396推荐的方法。但是PEP从未被接受,并且一直被推迟。事实上,Python核心开发人员似乎越来越支持不包含__version__属性,例如在Remove importlib_metadata.version..
更好的方法是:
获取特定包的详细信息
pip show <package_name>
它详细说明了package_name、版本、作者、位置等。
$ pip show numpy
Name: numpy
Version: 1.13.3
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: numpy-discussion@python.org
License: BSD
Location: c:\users\prowinjvm\appdata\local\programs\python\python36\lib\site-packages
Requires:
查看详细信息:>>> pip help
应该更新PIP以实现这一点。
pip install --upgrade pip
在Windows上,推荐的命令是:
python -m pip install --upgrade pip
一个列出所有包的Python程序(你可以把它复制到file requirements.txt):
from pip._internal.utils.misc import get_installed_distributions
print_log = ''
for module in sorted(get_installed_distributions(), key=lambda x: x.key):
print_log += module.key + '~=' + module.version + '\n'
print(print_log)
输出如下所示:
asn1crypto~=0.24.0
attrs~=18.2.0
automat~=0.7.0
beautifulsoup4~=4.7.1
botocore~=1.12.98
模块。__version__是一个很好的尝试,但它并不总是有效。
如果你不想退出,并且你正在使用pip 8或9,你仍然可以使用pip.get_installed_distribution()从Python内部获取版本:
这里的解决方案适用于pip 8和9,但在pip 10中,该函数已从pip中移动。get_installed_distribution到pip._internal.utils.misc。get_installed_distribution显式地指出它不供外部使用。如果您正在使用pip 10+,那么依赖它不是一个好主意。
import pip
pip.get_installed_distributions() # -> [distribute 0.6.16 (...), ...]
[
pkg.key + ': ' + pkg.version
for pkg in pip.get_installed_distributions()
if pkg.key in ['setuptools', 'statlib', 'construct']
] # -> nicely filtered list of ['setuptools: 3.3', ...]