我使用setuptools安装了Python模块construct和statlib:

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

如何从命令行检查它们的版本?


当前回答

你可以先安装这样的包,然后检查它的版本:

pip install package
import package
print(package.__version__)

它会给你一个打包的版本。

其他回答

在搜索了互联网之后,试图弄清楚如何确保我正在运行的模块的版本(显然是python_is_terrible . exe)。__version__在Python 2中不是一个东西?)从字面上看,这些答案都不适用于我的场景……

然后我想了一会儿,意识到基本原理……失败30分钟后…

假设模块已经安装并且可以导入


Python 3.7

>>> import sys,sqlite3
>>> sys.modules.get("sqlite3").version
'2.6.0'
>>> ".".join(str(x) for x in sys.version_info[:3])
'3.7.2'

Python 2.7

>>> import sys,sqlite3
>>> sys.modules.get("sqlite3").version
'2.6.0'
>>> ".".join(str(x) for x in sys.version_info[:3])
'2.7.11'

字面上就是这样…

你可以试试这个:

pip list

这将输出所有包及其版本。

输出

前面的答案没有解决我的问题,但这段代码做到了:

import sys 
for name, module in sorted(sys.modules.items()): 
  if hasattr(module, '__version__'): 
    print name, module.__version__ 

使用pip show查找版本!

# In order to get the package version, execute the below command
pip show YOUR_PACKAGE_NAME | grep Version

您可以使用pip show YOUR_PACKAGE_NAME -它会提供包的所有细节。这也适用于Windows。

grep Version在Linux中用于过滤出版本并显示它。

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)"