Pip install u что значит
Перейти к содержимому

Pip install u что значит

  • автор:

What does the "-U" option stand for in pip install -U

Despite a ton of Googling, I can’t find any docs for pip’s command line options/arguments. What does pip install -U mean? Does anyone have a link to a list of pip’s options and arguments?

zakdances's user avatar

1 Answer 1

Type pip install -h to list help:

-U, —upgrade Upgrade all packages to the newest available version

So, if you already have a package installed, it will upgrade the package for you. Without the -U switch it’ll tell you the package is already installed and exit.

Each pip subcommand has its own help listing. pip -h shows you overall help, and pip [subcommand] -h gives you help for that sub command, such as install .

You can also find the full reference documentation online; the General Options section covers switches available for every pip subcommand, while each subcommand has a separate Options section to cover subcommand-specific switches; see the pip install options section, for example.

What is the use of -U in the pip install command?

dessert's user avatar

This option upgrades all packages. From man pip /INSTALL OPTIONS:

dessert's user avatar

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.6.15.43498

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

pip install#

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).

Obtaining information about what was installed#

The install command has a —report option that will generate a JSON report of what pip has installed. In combination with the —dry-run and —ignore-installed it can be used to resolve a set of requirements without actually installing them.

The report can be written to a file, or to standard output (using —report — in combination with —quiet ).

The format of the JSON report is described in Installation Report .

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

This section has been moved to Requirements File Format .

This section has been moved to Requirement Specifiers .

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.

This is now covered in VCS Support .

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

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

This is now covered in HTTPS Certificates .

This is now covered in Caching .

This is now covered in Caching .

Hash checking mode

This is now covered in Secure installs .

Local Project Installs

Build System Interface

Options#

-r , —requirement <file> #

Install from the given requirements file. This option can be used multiple times.

-c , —constraint <file> #

Constrain versions using the given constraints file. This option can be used multiple times.

Don’t install package dependencies.

Include pre-release and development versions. By default, pip only finds stable versions.

-e , —editable <path/url> #

Install a project in editable mode (i.e. setuptools “develop mode”) from a local project path or a VCS url.

Don’t actually install anything, just print what would be. Can be used in combination with —ignore-installed to ‘resolve’ the requirements.

Install packages into <dir>. By default this will not replace existing files/folders in <dir>. Use —upgrade to replace existing packages in <dir> with new versions.

Only use wheels compatible with <platform>. Defaults to the platform of the running system. Use this option multiple times to specify multiple platforms supported by the target interpreter.

The Python interpreter version to use for wheel and “Requires-Python” compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. “3” for 3.0.0, “3.7” for 3.7.0, or “3.7.3”). A major-minor version can also be given as a string without dots (e.g. “37” for 3.7.0).

Only use wheels compatible with Python implementation <implementation>, e.g. ‘pp’, ‘jy’, ‘cp’, or ‘ip’. If not specified, then the current interpreter implementation is used. Use ‘py’ to force implementation-agnostic wheels.

Only use wheels compatible with Python abi <abi>, e.g. ‘pypy_41’. If not specified, then the current interpreter abi tag is used. Use this option multiple times to specify multiple abis supported by the target interpreter. Generally you will need to specify —implementation, —platform, and —python-version when using this option.

Install to the Python user install directory for your platform. Typically

/.local/, or %APPDATA%Python on Windows. (See the Python documentation for site.USER_BASE for full details.)

Install everything relative to this alternate root directory.

Installation prefix where lib, bin and other top-level folders are placed. Note that the resulting installation may contain scripts and other resources which reference the Python interpreter of pip, and not that of —prefix . See also the —python option if the intention is to install packages into another (possibly pip-free) environment.

Directory to check out editable projects into. The default in a virtualenv is “<venv path>/src”. The default for global installs is “<current dir>/src”.

Upgrade all specified packages to the newest available version. The handling of dependencies depends on the upgrade-strategy used.

Determines how dependency upgrading should be handled [default: only-if-needed]. “eager” — dependencies are upgraded regardless of whether the currently installed version satisfies the requirements of the upgraded package(s). “only-if-needed” — are upgraded only when they do not satisfy the requirements of the upgraded package(s).

Reinstall all packages even if they are already up-to-date.

Ignore the installed packages, overwriting them. This can break your system if the existing package is of a different version or was installed with a different package manager!

Ignore the Requires-Python information.

Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.

Use PEP 517 for building source distributions (use —no-use-pep517 to force legacy behaviour).

Check the build dependencies when PEP517 is used.

Allow pip to modify an EXTERNALLY-MANAGED Python installation

-C , —config-settings <settings> #

Configuration settings to be passed to the PEP 517 build backend. Settings take the form KEY=VALUE. Use multiple —config-settings options to pass multiple keys to the backend.

Extra global options to be supplied to the setup.py call before the install or bdist_wheel command.

Compile Python source files to bytecode

Do not compile Python source files to bytecode

Do not warn when installing scripts outside PATH

Do not warn about broken dependencies

Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either “:all:” to disable all binary packages, “:none:” to empty the set (notice the colons), or one or more package names with commas between them (no colons). Note that some packages are tricky to compile and may fail to install when this option is used on them.

Do not use source packages. Can be supplied multiple times, and each time adds to the existing value. Accepts either “:all:” to disable all source packages, “:none:” to empty the set, or one or more package names with commas between them. Packages without binary distributions will fail to install when this option is used on them.

Prefer older binary packages over newer source packages.

Require a hash to check each requirement against, for repeatable installs. This option is implied when any package in a requirements file has a —hash option.

Specify whether the progress bar should be used [on, off] (default: on)

Action if pip is run as a root user. By default, a warning message is shown.

Generate a JSON file describing what pip did to install the provided requirements. Can be used in combination with —dry-run and —ignore-installed to ‘resolve’ the requirements. When — is used as file name it writes to stdout. When writing to stdout, please combine with the —quiet option to avoid mixing pip logging output with JSON output.

Don’t clean up build directories.

Base URL of the Python Package Index (default https://pypi.org/simple). This should point to a repository compliant with PEP 503 (the simple repository API) or a local directory laid out in the same format.

Extra URLs of package indexes to use in addition to —index-url. Should follow the same rules as —index-url.

Ignore package index (only looking at —find-links URLs instead).

If a URL or path to an html file, then parse for links to archives such as sdist (.tar.gz) or wheel (.whl) files. If a local path or file:// URL that’s a directory, then look for archives in the directory listing. Links to VCS project URLs are not supported.

Examples#

Install SomePackage and its dependencies from PyPI using Requirement Specifiers

Pip для Python — что это?

WebDev_Deep_5.07_site-5020-c94b93.png

В этой статье пойдет разговор о pip для Python — что это, зачем применяется, как устанавливается, какие нюансы работы надо знать. Материал предназначен для начинающих разработчиков.

Pip (пип) — система управления пакетами, установка которой необходима для управления программными пакетами на Python. Но прежде, чем устанавливать pip на Python, давайте поговорим о пакете — что это, чем он отличается от модуля, как с ним работать.

Применительно к Python у термина существуют два значения: 1) Python-пакеты — это Py-дополнения, приложения или утилиты, которые можно устанавливать из внешнего репозитория: Bitbucket, Github, Google Code либо официального Python Package Index (PyPI). Речь идет о пакетах, находящихся в центральном репозитории PyPI («пипей»). Они хранятся на сервере в архивированном виде (.zip и .tar), а также в дополнительной упаковке .egg (старый формат) либо .whl. Сценарий установки setup.py присутствует в составе пакета, хранящего сведения о зависимостях — прочих модулях, без которых пакет функционировать не будет.

2) Рассмотрим другую сторону вопроса. Если мы говорим про архитектуру приложения на «Пайтоне», то пакет — это каталог, содержащий файл init.py, а также (опционально) и другие файлы .py. Таким образом, к примеру, большая Python-программа разбивается на модули. Под модулем понимается файл с исходным кодом, который без проблем применяется в других приложениях в качестве заготовки для будущих проектов либо как часть фреймворка/библиотеки. Однако это не имеет прямого отношения к теме нашей заметки, поэтому далее будем говорить лишь о Python-пакетах из репозиториев.

Продолжаем. Чтобы устанавливать пакеты в Python со всеми зависимостями, применяют менеджер пакетов pip либо модуль easy_install . Чаще всего рекомендуют использовать pip. Но если у вас присутствует инфраструктура на пакетах .egg (их «пип» не открывает), то потребуется easy_install .

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

Установка pip затруднений не вызывает. Мало того, если вы применяете виртуальные окружения на базе virtualenv и venv, то система «пип» уже установлена.

Начиная с «Пайтон» версии 3.4 (а для 2-го «Пайтона» — с 2.7.9), «пип» поставляется одновременно с интерпретатором. Если же говорить о более ранних версиях, то устанавливать менеджер пакетов pip нужно вручную. И вот здесь у нас есть два варианта: 1. Установка посредством скрипта get_pip.py . Главный плюс — скорость. 2. Установка с помощью setuptools. Здесь кроме «пип» мы сможем использовать и easy_install .

Как выглядит установка pip на практике? Вариант 1

Рассмотрим вариант установки с помощью скрипта. Для этого скачиваем get_pip.py , а потом запускаем его в консоли. Терминал можно открыть с помощью команды Win+R>»cmd»>OK, после чего написать:

Далее установщик всё сделает сам. А если надо, то попутно установит и wheel (если нужно будет распаковать .whl), и setuptools. Да, если вы хотите запретить установку дополнительных инструментов, добавьте в строку ключи —no-wheels и/или —no-setuptools.

Кстати, если возникнет ошибка, то существует вероятность, что в переменной среды $PATH не прописан путь к Python. Чтобы решить проблему, найдите данную переменную в системном реестре и задайте её значение. Также можно указывать каждый раз полный путь до python.exe, а потом имя исполняемого Py-файла:

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

Вариант 2

Здесь тоже установка не вызывает сложностей. Вам надо скачать архив с setuptools из PYPI и распаковать его в отдельный каталог. После этого в терминале перейдите в директорию с файлом setup.py и напишите:

Если хотите обновить pip в Windows, тогда:

Не сработало? Пропишите путь к папке с pip в $PATH.

Установка пакета в pip

1-20219-282863.png

Что же, пришло время запустить «пип» и начать устанавливать Python-пакеты путём короткой команды из консоли:

Да, если установка производится в операционную среду Windows, тогда перед pip нужно добавлять «python -m». Кстати, обновить пакет в Python тоже несложно посредством простой команды:

Следующая команда вам пригодится, если у вас последняя версия пакета, но есть желание принудительно переустановить его:

Хотите посмотреть список пакетов, установленных на Python? Используйте следующую команду:

Если желаете найти конкретный пакет, зная его имя, подойдёт «pip search». Да и вообще, вы можете узнать все команды в справке, написав «pip help».

Как удалять пакеты в Python?

Иногда пакет в Python больше не нужен, поэтому его можно легко удалить:

Устанавливаем пакеты в Python, не используя pip

Установка возможна с помощью модуля easy_install . Он умеет устанавливать как обычные пакеты, так и .egg, правда, последний формат сегодня используется довольно редко, поэтому он не поддерживается pip.

Если вас интересует установка посредством easy_install , ознакомьтесь сначала с важными минусами этого способа: — модуль не удаляет пакеты в Python; — easy_install может пытаться устанавливать недозагруженный пакет.

После установки setuptools вы можете сразу использовать easy_install . Данный модуль хранится в папке Scripts вашего интерпретатора. И если путь в $PATH прописан верно, то ставить пакеты из PYPI вы сможете простой и короткой командой:

Чтобы выполнить обновление (upgrade pip), перед именем пакета и после install достаточно поставить ключ -U.

Вот, к примеру, как выглядит команда обновления для операционной системы Windows:

Откатиться до нужной вам версии можно следующим образом:

Хотите скачать пакет для Python из альтернативного источника? Задайте URL либо локальный адрес на ПК:

Желаете узнать об опциях easy_install? Выполните запуск с ключом -h:

Кстати, пакеты, которые установлены с помощью easy_install , хранятся в файле easy-install.pth списком в директории /libs/site-packages/.

И ещё один момент: пакеты, установленные посредством easy_install , можно удалять с помощью «пип». Если же он отсутствует, вы можете удалить пакет вручную, стерев сведения о нём из easy-install.pth.

При необходимости вы можете найти определенный пакет. Искать можно следующим образом:

pip search «your_query»

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

Pip eel для Python — что это?

Eel — специальная библиотека, позволяющие создавать современные программные приложения на «Питоне» с красивым интерфейсом. Но прежде, чем начать работать с этой библиотекой, ее надо установить. Однако инсталляция eel происходит точно так же, как и в случае с любым другим модулем «Питона»:

Более подробно на эту тему читайте здесь.

Что же, теперь вы знаете о pip для Python — что это, как используется, как установить pip. Также умеете устанавливать и удалять пакеты для «Питона».

Если же хотите освоить этот язык программирования на более высоком уровне, воспользуйтесь курсами OTUS!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *