Nice programing

파이썬 모듈의 버전을 확인하는 방법은 무엇입니까?

nicepro 2020. 10. 3. 11:50
반응형

파이썬 모듈의 버전을 확인하는 방법은 무엇입니까?


방금 파이썬 모듈을 설치했습니다 : construct그리고 다음 statlibsetuptools같이 :

# Install setuptools to be able to download the following
sudo apt-get install python-setuptools

# Install statlib for lightweight statistical tools
sudo easy_install statlib

# Install construct for packing/unpacking binary data
sudo easy_install construct

나는 그들의 버전을 (프로그래밍 방식으로) 확인할 수 있기를 원합니다. python --version명령 줄에서 실행할 수 있는 것과 동일한 기능이 있습니까?

내 파이썬 버전은 2.7.3.


easy_install 대신 pip를 사용하는 것이 좋습니다 . pip를 사용하면 설치된 모든 패키지와 해당 버전을 다음과 같이 나열 할 수 있습니다.

pip freeze

대부분의 Linux 시스템에서 관심있는 특정 패키지에 대한 행을 찾기 위해 이를 파이프 grep(또는 findstrWindows에서) 할 수 있습니다.

Linux:
$ pip freeze | grep lxml
lxml==2.3

Windows:
c:\> 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__)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute '__version__'

마지막으로 질문의 명령에 접두사가 붙기 sudo때문에 글로벌 Python 환경에 설치하는 것으로 보입니다. Python 가상 환경 관리자 (예 : virtualenvwrapper)를 살펴 보는 것이 좋습니다.


당신은 시도 할 수 있습니다

>>> import statlib
>>> print statlib.__version__

>>> import construct
>>> print contruct.__version__

라이브러리 pkg_resources와 함께 배포 된 모듈을 사용하십시오 setuptools. get_distribution메서드에 전달하는 문자열 은 PyPI 항목과 일치해야합니다.

>>> import pkg_resources
>>> pkg_resources.get_distribution("construct").version
'2.5.2'

명령 줄에서 실행하려면 다음을 수행 할 수 있습니다.

python -c "import pkg_resources; print(pkg_resources.get_distribution('construct').version)"

get_distribution메서드에 전달하는 문자열은 가져 오려는 모듈 이름이 아니라 PyPI에 등록 된 패키지 이름이어야합니다.

불행히도 이것들은 항상 똑같은 것은 아닙니다 (예를 들어 당신은 pip install memcached,하지만 import memcache).


나는 이것이 도움이 될 수 있다고 생각하지만 먼저 show실행하기 위해 패키지를 설치 pip show한 다음 show를 사용하여 버전을 찾으십시오!

sudo pip install show
# in order to get package version execute the below command
sudo pip show YOUR_PACKAGE_NAME | grep Version

이를 수행하는 더 좋은 방법은 다음과 같습니다.


특정 패키지에 대한 자세한 내용은

pip show <package_name>

Package_name, 버전, 작성자, 위치 등을 자세히 설명합니다.


$ pip show numpy
Name: numpy
Version: 1.13.3
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: numpy-discussion@python.org
License: BSD
Location: c:\users\prowinjvm\appdata\local\programs\python\python36\lib\site-packages
Requires:

상세 사항은: >>> pip help


pip 이렇게하려면 업데이트해야합니다.

pip install --upgrade pip

Windows에서 권장하는 명령은 다음과 같습니다.

python -m pip install --upgrade pip


python3에서 인쇄 주위에 괄호가 있습니다.

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

module.__version__ 가장 먼저 시도하는 것이 좋지만 항상 작동하지는 않습니다.

셸 아웃하고 싶지 않고 pip 8 또는 9를 사용 pip.get_installed_distributions()하는 경우 에도를 사용 하여 Python 내에서 버전을 가져올 수 있습니다.

업데이트 : 여기의 솔루션은 pip 8 및 9에서 작동하지만 pip 10에서는 외부 사용을위한 것이 아님을 명시 적으로 나타 내기 pip.get_installed_distributions위해 함수가에서로 이동되었습니다 pip._internal.utils.misc.get_installed_distributions. pip 10 이상을 사용하는 경우 의존하는 것은 좋지 않습니다.

import pip

pip.get_installed_distributions()  # -> [distribute 0.6.16 (...), ...]

[
    pkg.key + ': ' + pkg.version
    for pkg in pip.get_installed_distributions()
    if pkg.key in ['setuptools', 'statlib', 'construct']
] # -> nicely filtered list of ['setuptools: 3.3', ...]

The previous answers did not solve my problem, but this code did:

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

You can use this command in Command prompt

pip show Modulename

ex : pip show xlrd

you will get output like this with all details.

Name: xlrd
Version: 1.2.0
Summary: Library for developers to extract data from Microsoft Excel (tm) spreadsheet files
Home-page: http://www.python-excel.org/
Author: John Machin
Author-email: sjmachin@lexicon.net
License: BSD
Location: c:\users\rohit.chaurasiya\appdata\local\programs\python\python37\lib\site-packages
Requires:
Required-by:

Use dir() to find out if the module has a __version__ attribute at all.

>>> 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']

You can use importlib_metadata library for this.

If you're on python <3.8, first install it with:

pip install importlib_metadata

Since python 3.8 it's included in the standard library.

Then, to check a package's version (in this example lxml) run:

>>> from importlib_metadata import version
>>> version('lxml')
'4.3.1'

Keep in mind that this works only for packages installed from PyPI. Also, you must pass a package name as an argument to the version method, rather than a module name that this package provides (although they're usually the same).


If the above methods do not work, it is worth trying the following in python:

import modulename

modulename.version
modulename.version_info

See Get Python Tornado Version?

Note, the .version worked for me on a few others besides tornado as well.


first add python, pip to your environment variables. so that you can execute your commands from command prompt. then simply give python command. then import the package

-->import scrapy

then print the version name

-->print(scrapy.__version__)

This will definitely work


Some modules don't have __version__ attribute, so the easiest way is check in the terminal: pip list


When you install Python, you also get the Python package manager, pip. You can use pip to get the versions of python modules. If you want to list all installed Python modules with their version numbers, use the following command:

$ pip freeze

You will get the output:

asn1crypto==0.22.0
astroid==1.5.2
attrs==16.3.0
Automat==0.5.0
backports.functools-lru-cache==1.3
cffi==1.10.0
...

To individually find the version number you can grep on this output on *NIX machines. For example:

$ pip freeze | grep PyMySQL

PyMySQL==0.7.11 On windows, you can use findstr instead of grep. For example:

PS C:\> pip freeze | findstr PyMySql

PyMySQL==0.7.11

If you want to know the version of a module within a Python script, you can use the __version__ attribute of the module to get it. Note that not all modules come with a __version__ attribute. For example,

>>> import pylint
>>> pylint.__version__
'1.7.1'

Assuming we are using Jupyter Notebook (if using Terminal, drop the exclamation marks):

1) if the package (e.g. xgboost) was installed with pip:

!pip show xgboost
!pip freeze | grep xgboost
!pip list | grep xgboost

2) if the package (e.g. caffe) was installed with conda:

!conda list caffe

This works in Jupyter Notebook on Windows, too! As long as Jupyter is launched from a bash-compliant command line such as Git Bash (MingW64), the solutions given in many of the answers can be used in Jupyter Notebook on Windows systems with one tiny tweak.

I'm running windows 10 Pro with Python installed via Anaconda, and the following code works when I launch Jupyter via Git Bash (but does not when I launch from the Anaconda prompt).

The tweak: Add an exclamation mark (!) in front of pip to make it !pip.

>>>!pip show lxml | grep Version
Version: 4.1.0

>>>!pip freeze | grep lxml
lxml==4.1.0

>>>!pip list | grep lxml
lxml                               4.1.0                  

>>>!pip show lxml
Name: lxml
Version: 4.1.0
Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
Home-page: http://lxml.de/
Author: lxml dev team
Author-email: lxml-dev@lxml.de
License: BSD
Location: c:\users\karls\anaconda2\lib\site-packages
Requires: 
Required-by: jupyter-contrib-nbextensions

To get a list of non-standard (pip) modules imported in the current module:

[{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() 
   if pkg.key in set(sys.modules) & set(globals())]

Result:

>>> import sys, pip, nltk, bs4
>>> [{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() if pkg.key in set(sys.modules) & set(globals())]
[{'pip': '9.0.1'}, {'nltk': '3.2.1'}, {'bs4': '0.0.1'}]

Note:

This code was put together from solutions both on this page and from How to list imported modules?


Quick python program to list all packges (you can copy it to 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)

The output would look like:

asn1crypto~=0.24.0
attrs~=18.2.0
automat~=0.7.0
beautifulsoup4~=4.7.1
botocore~=1.12.98

(see also https://stackoverflow.com/a/56912280/7262247)

I found it quite unreliable to use the various tools available (including the best one pkg_resources mentioned by Jakub Kukul' answer), as most of them do not cover all cases. For example

  • built-in modules
  • modules not installed but just added to the python path (by your IDE for example)
  • two versions of the same module available (one in python path superseding the one installed)

Since we needed a reliable way to get the version of any package, module or submodule, I ended up writing getversion. It is quite simple to use:

from getversion import get_module_version
import foo
version, details = get_module_version(foo)

See the documentation for details.


Building on Jakub Kukul's answer I found a more reliable way to solve this problem.

The main problem of that approach is that requires the packages to be installed "conventionally" (and that does not include using pip install --user), or be in the system PATH at Python initialisation.

To get around that you can use pkg_resources.find_distributions(path_to_search). This basically searches for distributions that would be importable if path_to_search was in the system PATH.

We can iterate through this generator like this:

avail_modules = {}
distros = pkg_resources.find_distributions(path_to_search)
for d in distros:
    avail_modules[d.key] = d.version

This will return a dictionary having modules as keys and their version as value. This approach can be extended to a lot more than version number.

Thanks to Jakub Kukul for pointing to the right direction


I had the same problem, I tried to uninstall both modules: serialand pyserial. Then I reinstalled pyserial ONLY and it worked perfectly.

참고URL : https://stackoverflow.com/questions/20180543/how-to-check-version-of-python-modules

반응형