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

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

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


当前回答

这个答案是为Windows用户准备的。正如在所有其他答案中建议的那样,你可以这样使用语句:

import [type the module name]
print(module.__version__) # module + '.' + double underscore + version + double underscore

但是,有一些模块即使在使用上面的方法后也不打印它们的版本。所以,你可以简单地做:

Open the command prompt. Navigate to the file address/directory by using cd (file address) where you've kept your Python and all supporting modules installed. If you have only one Python interpreter on your system, the PyPI packages are normally visible in the directory/folder: Python → Lib → site-packages. use the command "pip install [module name]" and hit Enter. This will show you a message as "Requirement already satisfied: file address\folder name (with version)". See the screenshot below for example: I had to know the version of a pre-installed module named "Selenium-Screenshot". It correctly showed as 1.5.0:

其他回答

在搜索了互联网之后,试图弄清楚如何确保我正在运行的模块的版本(显然是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 freeze的终端输出,并将模块标签和版本存储在字典中。

import os
os.system('pip freeze > tmpoutput')
with open('tmpoutput', 'r') as f:
    modules_version = f.read()
  
module_dict = {item.split("==")[0]:item.split("==")[-1] for item in modules_versions.split("\n")}

通过传递模块标签键来检索模块的版本,例如:

>>  module_dict["seaborn"]
'0.9.0'

在Python 3中用括号括起来的print:

>>> import celery
>>> print(celery.__version__)
3.1.14

一个列出所有包的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

如果您的生产系统被强化到无法理解的地步,所以它既没有pip也没有conda,这里有一个Bash替代pip冻结:

ls /usr/local/lib/python3.8/dist-packages | grep info | awk -F "-" '{print $1"=="$2}' | sed 's/.dist//g'

(请确保将dist-packages文件夹更新到当前的python版本,并忽略不一致的名称,例如,下划线vs.破折号)。

样本打印:

Flask==1.1.2
Flask_Caching==1.10.1
gunicorn==20.1.0
[..]