Подтвердить что ты не робот

Как проверить, есть ли у моего Python все необходимые пакеты?

У меня есть файл requirements.txt со списком пакетов, необходимых для моей виртуальной среды. Можно ли узнать, присутствуют ли все пакеты, упомянутые в файле. Если некоторые пакеты отсутствуют, как узнать, какие недостающие пакеты?

4b9b3361

Ответ 1

Питонический способ сделать это через pkg_resources API. Требования записываются в формате, понятном setuptools. Например:

Werkzeug>=0.6.1
Flask
Django>=1.3

Пример кода:

import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict

# dependencies can be any iterable with strings, 
# e.g. file line-by-line iterator
dependencies = [
  'Werkzeug>=0.6.1',
  'Flask>=0.9',
]

# here, if a dependency is not met, a DistributionNotFound or VersionConflict
# exception is thrown. 
pkg_resources.require(dependencies)

Ответ 2

Вы можете запустить pip freeze, чтобы узнать, что вы установили, и сравнить его с вашим файлом requirements.txt.

Если вы хотите установить отсутствующие модули, вы можете запустить pip install -r requirements.txt и установить какие-либо недостающие модули и сообщить вам в конце, какие из них отсутствовали и были установлены.

Ответ 3

В соответствии с ответом Zaur, если вы действительно используете файл requirements.txt, вам может понадобиться unit test, возможно, в tests/test_requirements.py, который подтверждает доступность пакетов.

Общий подход:

import pathlib
import unittest

import pip
import pkg_resources


class TestRequirements(unittest.TestCase):

    def test_requirements(self):  # pylint: disable=no-self-use
        """Recursively confirm that requirements are available.

        This implementation is tested to be compatible with pip 9.0.1.
        """
        requirements_path = pathlib.Path(__file__).parents[1] / 'requirements.txt'
        requirements = pip.req.parse_requirements(str(requirements_path), session=pip.download.PipSession())
        requirements = [str(r.req) for r in requirements]
        pkg_resources.require(requirements)

Обратите внимание, что в этом ответе используется pathlib, который доступен в Python 3, но не в Python 2. Если вы используете Python 2, сначала установите для него backport, который pathlib2.

Ответ 4

Вы можете создать virtualenv с доступом к пакетам сайта системы и проверить, установлен ли пакет (или другие зависимости) или нет. Таким образом, пакеты на самом деле не установлены (если вы просто хотите проверить). Пример использования virtualenv wrapper был бы следующим:

$ cat requirements.txt 
requests
simplejson

$ mkvirtualenv --system-site-packages test
Running virtualenv with interpreter /usr/bin/python2
New python executable in test/bin/python2
Also creating executable in test/bin/python
Installing setuptools, pip...done.

$ pip install -r requirements.txt
Downloading/unpacking requests (from -r requirements.txt (line 1))
  Downloading requests-2.10.0-py2.py3-none-any.whl (506kB): 506kB downloaded
Requirement already satisfied (use --upgrade to upgrade): simplejson in /usr/lib/python2.7/dist-packages (from -r requirements.txt (line 2))
Installing collected packages: requests
Successfully installed requests
Cleaning up...

$ pip install -r requirements.txt
Requirement already satisfied (use --upgrade to upgrade): requests in /home/yucer/.virtualenvs/test/lib/python2.7/site-packages (from -r requirements.txt (line 1))
Requirement already satisfied (use --upgrade to upgrade): simplejson in /usr/lib/python2.7/dist-packages (from -r requirements.txt (line 2))
Cleaning up...

$ deactivate

$ rmvirtualenv test
Removing test...

Ответ 5

Если require.txt похож:

django
oursql
sys
notexistingmodule

Тогда следующий script расскажет вам, какие модули отсутствуют:

#!/usr/bin/python3
fname = 'requirements.txt'
with open(fname, 'r', encoding='utf-8') as fhd:
    for line in fhd:
        try:
            exec("import " + line)
        except:
            print("[ERROR] Missing module:", line)

Это будет печатать:

[ERROR] Missing module: notexistingmodule