Pip install requirements txt linux

Pip: как устанавливать пакеты в Python

Pip: как устанавливать пакеты в Python

Pip — менеджер пакетов для Python, работа с ним осуществляется через командную строку. Pip не нужно устанавливать отдельно, если вы пользуетесь Python версии 2.7.9 и новее или версии 3.4 и новее. Если pip установлен, то можно ввести в командную строку:

Команды статье указаны для Windows, работа с pip в Linux может отличаться.

Вы получите справку по основным командам.

Установка pip для Python

Если pip не установлен, то нужно скачать скрипт. Выбирайте папку с номером вашей версии Python. После этого в командной строке перейдите в папку со скриптом и выполните команду:

Если pip установлен в папку ProgramFiles, то вам нужно запускать командную строку от администратора.

Если вы установили pip, но все равно получаете ошибку в консоли, нужно указать путь к файлу pip.exe в переменной Path. Для этого зайдите в свойства компьютера>Дополнительные параметры системы>Переменные среды. Здесь (в зависимости о версии Windows) либо добавьте путь к уже существующему через точку с запятой, либо просто нажмите создать и скопируйте путь в новое поле.

Если вам нужно обновить pip напишите в командной строке:

Управление пакетами

Чтобы выполнить установку пакета с сайта pypi.org введите в консоли:

Если вам нужно использовать несколько версий pip, то нужную можно указать так (начиная с версии pip 0.8):

Таким же образом можно выбирать версию Python:

Pip версии 1.5 и выше следует указывать так:

Чтобы обновить пакет введите:

Для удаления пакета используйте команду uninstall:

Флаг -m используется для того чтобы запустить установленный модуль, как скрипт (если написать pip без -m вы можете получить ошибку).

Revolut , Moscow, можно удалённо , По итогам собеседования

Вывести список всех установленных пакетов в файл можно с помощью :

При наличии такого файла, можно устанавливать пакеты группами:

Необходимые пакеты можно найти не заходя на сайт pyPi.org (в данный момент недоступно):

Чтобы узнать подробности об установленном пакете введите:

Проверить установлены ли все зависимости для ваших пакетов можно так:

Теперь, с этими знаниями, вы можете самостоятельно скачать пакет cowsay, зайти в python, и ввести этот текст:

Готово! У вас есть говорящая консольная корова:

Хинт для программистов: если зарегистрируетесь на соревнования Huawei Cup, то бесплатно получите доступ к онлайн-школе для участников. Можно прокачаться по разным навыкам и выиграть призы в самом соревновании.

Перейти к регистрации

Источник

Installing packages using pip and virtual environments¶

This guide discusses how to install packages using pip and a virtual environment manager: either venv for Python 3 or virtualenv for Python 2. These are the lowest-level tools for managing Python packages and are recommended if higher-level tools do not suit your needs.

This doc uses the term package to refer to a Distribution Package which is different from an Import Package that which is used to import modules in your Python source code.

Installing pip¶

pip is the reference Python package manager. It’s used to install and update packages. You’ll need to make sure you have the latest version of pip installed.

Debian and most other distributions include a python-pip package; if you want to use the Linux distribution-provided versions of pip, see Installing pip/setuptools/wheel with Linux Package Managers .

You can also install pip yourself to ensure you have the latest version. It’s recommended to use the system pip to bootstrap a user installation of pip:

Afterwards, you should have the latest version of pip installed in your user site:

The Python installers for Windows include pip. You can make sure that pip is up-to-date by running:

Afterwards, you should have the latest version of pip:

Installing virtualenv¶

If you are using Python 3.3 or newer, the venv module is the preferred way to create and manage virtual environments. venv is included in the Python standard library and requires no additional installation. If you are using venv, you may skip this section.

virtualenv is used to manage Python packages for different projects. Using virtualenv allows you to avoid installing Python packages globally which could break system tools or other projects. You can install virtualenv using pip.

Creating a virtual environment¶

venv (for Python 3) and virtualenv (for Python 2) allow you to manage separate package installations for different projects. They essentially allow you to create a “virtual” isolated Python installation and install packages into that virtual installation. When you switch projects, you can simply create a new virtual environment and not have to worry about breaking the packages installed in the other environments. It is always recommended to use a virtual environment while developing Python applications.

To create a virtual environment, go to your project’s directory and run venv. If you are using Python 2, replace venv with virtualenv in the below commands.

The second argument is the location to create the virtual environment. Generally, you can just create this in your project and call it env .

venv will create a virtual Python installation in the env folder.

You should exclude your virtual environment directory from your version control system using .gitignore or similar.

Activating a virtual environment¶

Before you can start installing or using packages in your virtual environment you’ll need to activate it. Activating a virtual environment will put the virtual environment-specific python and pip executables into your shell’s PATH .

You can confirm you’re in the virtual environment by checking the location of your Python interpreter:

Источник

requirements.txt — что это и зачем?

В исходниках множества Python-проектов можно встретить этот странный текстовый файл. Например, им пользуются urllib3, numpy, pandas, flake8 и куча других проектов. Давайте разберемся, что это такое, как этим пользоваться и зачем нам это нужно.

Гипотетическая предыстория

Давайте представим, что вы написали замечательный скрипт, который спрашивает у пользователя название города и выводит текущую температуру и общее состояние погоды:

Читайте также:  Amd raid drivers windows 10

Скрипт получился настолько хорош, что вы хотите поделиться им со всеми своими друзьями. К сожалению, друзья при попытке запустить вашу программу получают следующую ошибку:

Кажется, что скинуть только код недостаточно.

Или, допустим, что вы сами через полгода-год попытаетесь запустить эту же программу. За это время вы успели пару раз переустановить Python, переустановить ОС, отформатировать свой магнитный накопитель (используйте SSD — нет, я серьёзно!) или может быть вообще сменили компьютер. Почти уверен, что при запуске скрипта вы получите ровно ту же самую ошибку.

Зачастую, когда мы пишем код, мы полагаемся на какие-либо библиотеки или фреймворки. Это со всех сторон хорошо — это удобно, уменьшает размер программы во много раз, позволяет не думать о мелких деталях, а решать свою конкретную задачу, опираясь на высокоуровневые абстракции. Но, к сожалению, есть «но» — такие библиотеки становятся частью вашей программы, ваш код становится зависим. Это значит, что ваш код больше не сможет работать сам по себе, для его работы должны быть установлены все зависимости.

Если ваша программа небольшая (состоит из пары файлов), то можно довольно легко просмотреть её глазами, найти там все инструкции import , отсеять из них импорты из стандартной библиотеки (вы ведь знаете модули стандартной библиотеки наизусть, да?), и таким образом восстановить список внешних зависимостей программы, которые устанавливаются через pip . Чем крупнее проект, тем сложнее это сделать. Бывают ситуации, когда по коду вообще нельзя понять, что ему нужна определенная зависимость.

Я хочу сказать, что намного мудрее составлять этот список зависимостей сразу же и просто поддерживать его в актуальном состоянии по мере развития проекта.

requirements.txt — это список внешних зависимостей

Сообщество Python исповедует идеологию «простое лучше, чем сложное». Наверное, поэтому для хранения списка зависимостей сообщество выбрало самый простой из возможных форматов — текстовый файл, где на каждой строке перечислено ровно по одной зависимости.

Стоит отметить, что requirements.txt не является стандартом, т.е. нет документа, который описывал бы требования к этому файлу. Скорее, это просто распространённая практика в сообществе, которая, наверное, возникла спонтанно и хорошо прижилась.

Не обязательно называть файл именно requirements.txt , можно назвать его как угодно, лишь бы его назначение оставалось понятно. Я встречал такие вариации, как requirements-dev.txt , test-requirements.txt , requirements/docs.txt и другие.

Вот пример самого простого такого файла (кстати, именно этим файлом можно описать зависимости, которые нужны для запуска нашего скрипта с погодой):

Если бы было несколько зависимостей, то файл выглядел бы так:

Можно указать конкретную версию зависимости. Если версия не указана, то считается, что нужна последняя доступная:

Можно указывать диапазоны и другие более сложные «спецификаторы версий». В целом, в requirements.txt можно писать любые «запросы», которые понимает команда pip install :

Как пользоваться

Команда pip install умеет читать такие файлы, если передать специальный флаг:

Таким образом, если requirements.txt будет иметь вот такое содержимое:

То следующие две команды будут иметь одинаковое действие:

Преимущества использования requirements.txt :

На таком маленьком примере разница может быть не очевидна, но когда список зависимостей разрастётся до определенного размера, то вам не захочется больше перечислять его в pip install напрямую.

Как бы ни поменялся файл requirements.txt , команда pip install -r requirements.txt не поменяется.

Так как это распространённое соглашение, то другим разработчикам будет достаточно увидеть этот файл, чтобы понять, что нужно сделать. Это здорово экономит время на чтении инструкций.

Как создать

Есть два подхода:

  • создавать этот файл вручную;
  • генерировать автоматически.

Главный принцип ручного подхода — если что-то поменялось в списке зависимостей (добавилась или удалилась зависимость, обновилась версия и т.д.), это изменение нужно отразить в requirements.txt .

Но можно использовать и встроенную в pip функциональность:

Команда pip freeze выводит все установленные в интерпретатор сторонние пакеты. Заметьте, что в список попали не только прямые зависимости ( pyowm ), но и подзависимости — это даже лучше, потому что вы сможете более точно воссоздать окружение по этому файлу.

Можно перенаправить вывод этой команды в файл при помощи стандартного консольного приема (работает и на Windows), и получить валидный файл requirements.txt :

Обратите внимание, что pip freeze выведет список пакетов в том окружении, в котором он запущен. Не забудьте активировать виртуальное окружение перед запуском этой команды, иначе получите список пакетов, установленных в глобальный интерпретатор. Кстати, у меня есть пост про виртуальные окружения, где объясняется как ими пользоваться.

Подытожим плюсы и минусы ручного и автоматического подходов:

  • Вручную:
    • минимальный файл, содержащий только прямые зависимости;
    • можно указывать сложные спецификаторы версий;
    • человеческий фактор — легко ошибиться или забыть что-нибудь;
  • pip freeze :
    • автоматически, быстро;
    • автоматически добавляет версии установленных пакетов;
    • в файл попадет всё дерево зависимостей, а не только прямые зависимости.

Можно использовать и смешанный подход: сгенерировать начальную версию файла при помощи pip freeze и допилить её затем руками, если у вас какая-то сложная нестандартная ситуация.

⚠️ Файл requirements.txt , конечно же, должен быть добавлен в систему контроля версий (git). Это такая же важная часть проекта, как и код. При этом виртуальное окружение не должно попадать в систему контроля версий. Оно должно воссоздаваться из requirements.txt .

Проблемы requirements.txt

Некоторые пакеты часто меняются, поэтому если вы не указываете конкретные версии, то в следующий раз при установке вы можете получить совсем другую среду. Это бывает особенно обидно, когда локально на машине разработчика всё работает правильно, но при деплое на боевой сервер программа либо работает иначе, либо вообще отказывается запускаться. Поэтому обязательно фиксируйте версии пакетов в requirements.txt — это сделает разные окружения хотя бы примерно похожими.

Почему «хотя бы примерно»? Практика показывает, что зафиксировать версию пакета недостаточно. Иногда случается, что под одной версией пакета в разное время может находиться совершенно разный код. PyPI, конечно, не позволит перезаписать уже опубликованную версию, но, например, ваш приватный корпоративный индекс пакетов может быть не таким строгим.

Чтобы действительно гарантировать, что вы устанавливаете те пакеты, что и ожидали, нужно рассчитывать и сверять их контрольные суммы. requirements.txt может содержать хэши пакетов, но, к сожалению, на данный момент нет простого стандартного способа как их туда положить, кроме как вручную (сложно). В качестве альтернативы опять предлагаю присмотреться к таким проектам, как poetry (хранит хэши в poetry.lock ) и pipenv (хранит хэши в Pipfile.lock ), где эта проблема решена хорошо, и вам не придётся переживать о воспроизводимости ваших сборок. Если всё-таки хочется добиться такого же эффекта при помощи requirements.txt , то можно посмотреть на такие проекты как pip-tools (пример использования) и hashin .

Заключение

requirements.txt — это очень популярный способ хранения списка внешних зависимостей проекта, поэтому вам определенно нужно уметь работать с такими файлами. Однако этот способ хранения списка зависимостей не лишён недостатков, поэтому если вы начинаете новый проект, то я предлагаю вам лучше использовать для этого poetry или pipenv .

Читайте также:  Эмулятор геймпада для pc windows 10 xpadder

Для тренировки можно попытаться запустить скрипт с погодой. Все исходники лежат здесь.

Дополнительное чтение

Конечно, я затронул лишь верхушку айсберга. На самом деле, requirements -файлы немножко сложнее.

Подпишитесь!

Чтобы получить уведомление о новом посте можно:

Источник

pip install¶

Usage¶

Description¶

Install packages from:

PyPI (and other indexes) using requirement specifiers.

VCS project urls.

Local project directories.

Local or remote source archives.

pip also supports installing from “requirements files”, which provide an easy way to specify a whole environment to be installed.

Overview¶

pip install has several stages:

Identify the base requirements. The user supplied arguments are processed here.

Resolve dependencies. What will be installed is determined here.

Build wheels. All the dependencies that can be are built into wheels.

Install the packages (and uninstall anything being upgraded/replaced).

Note that pip install prefers to leave the installed version as-is unless —upgrade is specified.

Argument Handling¶

When looking at the items to be installed, pip checks what type of item each is, in the following order:

Project or archive URL.

Local directory (which must contain a setup.py , or pip will report an error).

Local file (a sdist or wheel format archive, following the naming conventions for those formats).

A requirement, as specified in PEP 440.

Each item identified is added to the set of requirements to be satisfied by the install.

Working Out the Name and Version¶

For each candidate item, pip needs to know the project name and version. For wheels (identified by the .whl file extension) this can be obtained from the filename, as per the Wheel spec. For local directories, or explicitly specified sdist files, the setup.py egg_info command is used to determine the project metadata. For sdists located via an index, the filename is parsed for the name and project version (this is in theory slightly less reliable than using the egg_info command, but avoids downloading and processing unnecessary numbers of files).

Any URL may use the #egg=name syntax (see VCS Support ) to explicitly state the project name.

Satisfying Requirements¶

Once pip has the set of requirements to satisfy, it chooses which version of each requirement to install using the simple rule that the latest version that satisfies the given constraints will be installed (but see here for an exception regarding pre-release versions). Where more than one source of the chosen version is available, it is assumed that any source is acceptable (as otherwise the versions would differ).

Installation Order¶

This section is only about installation order of runtime dependencies, and does not apply to build dependencies (those are specified using PEP 518).

As of v6.1.0, pip installs dependencies before their dependents, i.e. in “topological order.” This is the only commitment pip currently makes related to order. While it may be coincidentally true that pip will install things in the order of the install arguments or in the order of the items in a requirements file, this is not a promise.

In the event of a dependency cycle (aka “circular dependency”), the current implementation (which might possibly change later) has it such that the first encountered member of the cycle is installed last.

For instance, if quux depends on foo which depends on bar which depends on baz, which depends on foo:

Prior to v6.1.0, pip made no commitments about install order.

The decision to install topologically is based on the principle that installations should proceed in a way that leaves the environment usable at each step. This has two main practical benefits:

Concurrent use of the environment during the install is more likely to work.

A failed install is less likely to leave a broken environment. Although pip would like to support failure rollbacks eventually, in the mean time, this is an improvement.

Although the new install order is not intended to replace (and does not replace) the use of setup_requires to declare build dependencies, it may help certain projects install from sdist (that might previously fail) that fit the following profile:

They have build dependencies that are also declared as install dependencies using install_requires .

python setup.py egg_info works without their build dependencies being installed.

For whatever reason, they don’t or won’t declare their build dependencies using setup_requires .

Requirements File Format¶

Each line of the requirements file indicates something to be installed, and like arguments to pip install , the following forms are supported:

For details on requirement specifiers, see Requirement Specifiers .

See the pip install Examples for examples of all these forms.

A line that begins with # is treated as a comment and ignored. Whitespace followed by a # causes the # and the remainder of the line to be treated as a comment.

A line ending in an unescaped \ is treated as a line continuation and the newline following it is effectively ignored.

Comments are stripped after line continuations are processed.

To interpret the requirements file in UTF-8 format add a comment # -*- coding: utf-8 -*- to the first or second line of the file.

The following options are supported:

Please note that the above options are global options, and should be specified on their individual lines. The options which can be applied to individual requirements are —install-option , —global-option and —hash .

For example, to specify —pre , —no-index and two —find-links locations:

If you wish, you can refer to other requirements files, like this:

You can also refer to constraints files , like this:

Using Environment Variables¶

Since version 10, pip supports the use of environment variables inside the requirements file. You can now store sensitive data (tokens, keys, etc.) in environment variables and only specify the variable name for your requirements, letting pip lookup the value at runtime. This approach aligns with the commonly used 12-factor configuration pattern.

You have to use the POSIX format for variable names including brackets around the uppercase name as shown in this example: $ . pip will attempt to find the corresponding environment variable defined on the host system at runtime.

There is no support for other variable expansion syntaxes such as $VARIABLE and %VARIABLE% .

Example Requirements File¶

Use pip install -r example-requirements.txt to install:

Читайте также:  Диагностика аппаратного raid linux

Requirement Specifiers¶

pip supports installing from a package index using a requirement specifier . Generally speaking, a requirement specifier is composed of a project name followed by optional version specifiers . PEP 508 contains a full specification of the format of a requirement. Since version 18.1 pip supports the url_req -form specification.

Since version 6.0, pip also supports specifiers containing environment markers like so:

Since version 19.1, pip also supports direct references like so:

Environment markers are supported in the command line and in requirements files.

Use quotes around specifiers in the shell when using > , , or when using environment markers. Don’t use quotes in requirement files. 1

Per-requirement Overrides¶

Since version 7.0 pip supports controlling the command line options given to setup.py via requirements files. This disables the use of wheels (cached or otherwise) for that package, as setup.py does not exist for wheels.

The —global-option and —install-option options are used to pass options to setup.py . For example:

The above translates roughly into running FooProject’s setup.py script as:

Note that the only way of giving more than one option to setup.py is through multiple —global-option and —install-option options, as shown in the example above. The value of each option is passed as a single argument to the setup.py script. Therefore, a line such as the following is invalid and would result in an installation error.

Pre-release Versions¶

Starting with v1.4, pip will only install stable versions as specified by pre-releases by default. If a version cannot be parsed as a compliant PEP 440 version then it is assumed to be a pre-release.

If a Requirement specifier includes a pre-release or development version (e.g. >=0.0.dev0 ) then pip will allow pre-release and development versions for that requirement. This does not include the != flag.

The pip install command also supports a —pre flag that enables installation of pre-releases and development releases.

VCS Support¶

This is now covered in VCS Support .

Finding Packages¶

pip searches for packages on PyPI using the HTTP simple interface, which is documented here and there.

pip offers a number of package index options for modifying how packages are found.

pip looks for packages in a number of places: on PyPI (if not disabled via —no-index ), in the local filesystem, and in any additional repositories specified via —find-links or —index-url . There is no ordering in the locations that are searched. Rather they are all checked, and the “best” match for the requirements (in terms of version number — see PEP 440 for details) is selected.

SSL Certificate Verification¶

Starting with v1.3, pip provides SSL certificate verification over HTTP, to prevent man-in-the-middle attacks against PyPI downloads. This does not use the system certificate store but instead uses a bundled CA certificate store. The default bundled CA certificate store certificate store may be overridden by using —cert option or by using PIP_CERT , REQUESTS_CA_BUNDLE , or CURL_CA_BUNDLE environment variables.

Caching¶

This is now covered in Caching

Wheel Cache¶

This is now covered in Caching

Hash-Checking Mode¶

Since version 8.0, pip can check downloaded package archives against local hashes to protect against remote tampering. To verify a package against one or more hashes, add them to the end of the line:

(The ability to use multiple hashes is important when a package has both binary and source distributions or when it offers binary distributions for a variety of platforms.)

The recommended hash algorithm at the moment is sha256, but stronger ones are allowed, including all those supported by hashlib . However, weaker ones such as md5, sha1, and sha224 are excluded to avoid giving a false sense of security.

Hash verification is an all-or-nothing proposition. Specifying a —hash against any requirement not only checks that hash but also activates a global hash-checking mode, which imposes several other security restrictions:

Hashes are required for all requirements. This is because a partially-hashed requirements file is of little use and thus likely an error: a malicious actor could slip bad code into the installation via one of the unhashed requirements. Note that hashes embedded in URL-style requirements via the #md5=. syntax suffice to satisfy this rule (regardless of hash strength, for legacy reasons), though you should use a stronger hash like sha256 whenever possible.

Hashes are required for all dependencies. An error results if there is a dependency that is not spelled out and hashed in the requirements file.

Requirements that take the form of project names (rather than URLs or local filesystem paths) must be pinned to a specific version using == . This prevents a surprising hash mismatch upon the release of a new version that matches the requirement specifier.

—egg is disallowed, because it delegates installation of dependencies to setuptools, giving up pip’s ability to enforce any of the above.

Hash-checking mode can be forced on with the —require-hashes command-line option:

This can be useful in deploy scripts, to ensure that the author of the requirements file provided hashes. It is also a convenient way to bootstrap your list of hashes, since it shows the hashes of the packages it fetched. It fetches only the preferred archive for each package, so you may still need to add hashes for alternatives archives using pip hash : for instance if there is both a binary and a source distribution.

The wheel cache is disabled in hash-checking mode to prevent spurious hash mismatch errors. These would otherwise occur while installing sdists that had already been automatically built into cached wheels: those wheels would be selected for installation, but their hashes would not match the sdist ones from the requirements file. A further complication is that locally built wheels are nondeterministic: contemporary modification times make their way into the archive, making hashes unpredictable across machines and cache flushes. Compilation of C code adds further nondeterminism, as many compilers include random-seeded values in their output. However, wheels fetched from index servers are the same every time. They land in pip’s HTTP cache, not its wheel cache, and are used normally in hash-checking mode. The only downside of having the wheel cache disabled is thus extra build time for sdists, and this can be solved by making sure pre-built wheels are available from the index server.

Hash-checking mode also works with pip download and pip wheel . See Repeatable Installs for a comparison of hash-checking mode with other repeatability strategies.

Источник

Оцените статью