我使用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
如何从命令行检查它们的版本?
当前回答
前面的答案没有解决我的问题,但这段代码做到了:
import sys
for name, module in sorted(sys.modules.items()):
if hasattr(module, '__version__'):
print name, module.__version__
其他回答
使用dir()来找出模块是否有__version__属性。
>>> import selenium
>>> dir(selenium)
['__builtins__', '__doc__', '__file__', '__name__',
'__package__', '__path__', '__version__']
>>> selenium.__version__
'3.141.0'
>>> selenium.__path__
['/venv/local/lib/python2.7/site-packages/selenium']
根据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指出了正确的方向。
在搜索了互联网之后,试图弄清楚如何确保我正在运行的模块的版本(显然是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 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)"