开发者

How do I get a python module's version number through code? [duplicate]

开发者 https://www.devze.com 2023-01-12 02:09 出处:网络
This question already has answers here开发者_如何学Python: Checking a Python module version at runtime
This question already has answers here开发者_如何学Python: Checking a Python module version at runtime (7 answers) Closed 3 years ago.

I'm trying to get the version number of a specific few modules that I use. Something that I can store in a variable.


Use pkg_resources(part of setuptools). Anything installed from PyPI at least has a version number. No extra package/module is needed.

>>> import pkg_resources
>>> pkg_resources.get_distribution("simplegist").version
'0.3.2'


Generalized answer from Matt's, do a dir(YOURMODULE) and look for __version__, VERSION, or version. Most modules like __version__ but I think numpy uses version.version


Starting Python 3.8, importlib.metadata can be used as a replacement for pkg_resources to extract the version of third-party packages installed via tools such as pip:

from importlib.metadata import version
version('wheel')
# '0.33.4'


I think it depends on the module. For example, Django has a VERSION variable that you can get from django.VERSION, sqlalchemy has a __version__ variable that you can get from sqlalchemy.__version__.


Some modules (e.g. azure) do not provide a __version__ string.

If the package was installed with pip, the following should work.

# say we want to look for the version of the "azure" module
import pip
for m in pip.get_installed_distributions():
    if m.project_name == 'azure':
        print(m.version)


 import sys
 import matplotlib as plt
 import pandas as pd
 import sklearn as skl
 import seaborn as sns

 print(sys.version)
 print(plt.__version__)
 print(pd.__version__)
 print(skl.__version__)
 print(sns.__version__)

The above code shows versions of respective modules: Sample O/P:

3.7.1rc1 (v3.7.1rc1:2064bcf6ce, Sep 26 2018, 14:21:39) [MSC v.1914 32 bit (Intel)] 3.1.0 0.24.2 0.21.2 0.9.0 (sys shows version of python )

0

精彩评论

暂无评论...
验证码 换一张
取 消