我使用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 >= 3.8:
如果您使用的是Python >= 3.8,则可以使用内置库中的模块。要检查包的版本(在这个例子中),运行:
>>> from importlib.metadata import version
>>> version('construct')
'4.3.1'
Python < 3.8:
使用随setuptools库分发的pkg_resources模块。注意,传递给get_distribution方法的字符串应该对应于PyPI条目。
>>> import pkg_resources
>>> pkg_resources.get_distribution('construct').version
'2.5.2'
边注:
请注意,传递给get_distribution方法的字符串应该是在PyPI中注册的包名,而不是您试图导入的模块名。不幸的是,它们并不总是相同的(例如,你安装了memcached,但导入了memcache)。 如果你想从命令行应用这个解决方案,你可以这样做:
python -c \
"import pkg_resources; print(pkg_resources.get_distribution('construct').version)"
其他回答
你可以试试
>>> import statlib
>>> print statlib.__version__
>>> import construct
>>> print contruct.__version__
这是PEP 396推荐的方法。但是PEP从未被接受,并且一直被推迟。事实上,Python核心开发人员似乎越来越支持不包含__version__属性,例如在Remove importlib_metadata.version..
使用pip而不是easy_install。
使用pip,通过以下方式列出所有已安装的软件包及其版本:
pip freeze
在大多数Linux系统上,您可以将其输送到grep(或Windows上的findstr),以查找您感兴趣的特定包的行。
Linux:
pip freeze | grep lxml
lxml = = 2.3
窗口:
pip freeze | findstr lxml
lxml = = 2.3
对于单个模块,您可以尝试__version__属性。然而,有一些模块没有它:
python -c "import requests; print(requests.__version__)"
2.14.2
python -c "import lxml; print(lxml.__version__)"
回溯(最近一次调用): 文件"<string>",第1行,在<模块> 'module'对象没有'version'属性
最后,由于您的问题中的命令带有sudo前缀,似乎您正在安装到全局python环境。我强烈建议研究一下Python虚拟环境管理器,例如virtualenvwrapper。
Python >= 3.8:
如果您使用的是Python >= 3.8,则可以使用内置库中的模块。要检查包的版本(在这个例子中),运行:
>>> from importlib.metadata import version
>>> version('construct')
'4.3.1'
Python < 3.8:
使用随setuptools库分发的pkg_resources模块。注意,传递给get_distribution方法的字符串应该对应于PyPI条目。
>>> import pkg_resources
>>> pkg_resources.get_distribution('construct').version
'2.5.2'
边注:
请注意,传递给get_distribution方法的字符串应该是在PyPI中注册的包名,而不是您试图导入的模块名。不幸的是,它们并不总是相同的(例如,你安装了memcached,但导入了memcache)。 如果你想从命令行应用这个解决方案,你可以这样做:
python -c \
"import pkg_resources; print(pkg_resources.get_distribution('construct').version)"
对于未定义字段__version__的情况:
try:
from importlib import metadata
except ImportError:
import importlib_metadata as metadata # python<=3.7
metadata.version("package")
或者,就像之前提到的那样:
import pkg_resources
pkg_resources.get_distribution('package').version
我建议在终端中打开一个Python shell(在您感兴趣的Python版本中),导入库,并获取其__version__属性。
>>> import statlib
>>> statlib.__version__
>>> import construct
>>> contruct.__version__
注1:我们必须考虑Python版本。如果已经安装了不同版本的Python,则必须在感兴趣的Python版本中打开终端。例如,使用Python 3.8打开终端可以(肯定会)提供与使用Python 3.5或Python 2.7打开不同版本的库。
注意2:我们避免使用print函数,因为它的行为依赖于Python 2或Python 3。我们不需要它,终端将显示表达式的值。