Pip install r requirements txt windows

Usage¶

Unix/macOS

python -m pip install [options] <requirement specifier> [package-index-options] ...
python -m pip install [options] -r <requirements file> [package-index-options] ...
python -m pip install [options] [-e] <vcs project url> ...
python -m pip install [options] [-e] <local project path> ...
python -m pip install [options] <archive url/path> ...

Windows

py -m pip install [options] <requirement specifier> [package-index-options] ...
py -m pip install [options] -r <requirements file> [package-index-options] ...
py -m pip install [options] [-e] <vcs project url> ...
py -m pip install [options] [-e] <local project path> ...
py -m pip install [options] <archive url/path> ...

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:

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

  2. Resolve dependencies. What will be installed is determined here.

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

  4. 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:

  1. Project or archive URL.

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

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

  4. A version specifier.

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¶

Note

This section is only about installation order of runtime dependencies, and
does not apply to build dependencies (those are specified using the
[build-system] table).

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:

Unix/macOS

$ python -m pip install quux
...
Installing collected packages baz, bar, foo, quux

$ python -m pip install bar
...
Installing collected packages foo, baz, bar

Windows

C:\> py -m pip install quux
...
Installing collected packages baz, bar, foo, quux

C:\> py -m pip install bar
...
Installing collected packages foo, baz, bar

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:

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

  2. 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:

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

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

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

Requirement Specifiers

This section has been moved to Requirement Specifiers.

Per-requirement Overrides

This is now covered in Requirements File Format.

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 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 (or the index given as
--index-url, if not disabled via --no-index), in the local filesystem,
and in any additional repositories specified via --find-links or
--extra-index-url. There is no priority in the locations that are searched.
Rather they are all checked, and the “best” match for the requirements (in
terms of version number — see the
specification for details) is selected.

See the pip install Examples.

SSL Certificate Verification

This is now covered in HTTPS Certificates.

Caching

This is now covered in Caching.

Wheel Cache

This is now covered in Caching.

Hash checking mode

This is now covered in Secure installs.

Local Project Installs

This is now covered in Local project installs.

Editable installs

This is now covered in Local project installs.

Build System Interface

This is now covered in Build System Interface.

Options¶

-r, —requirement <file>

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

(environment variable: PIP_REQUIREMENT)

-c, —constraint <file>

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

(environment variable: PIP_CONSTRAINT)

—no-deps

Don’t install package dependencies.

(environment variable: PIP_NO_DEPS, PIP_NO_DEPENDENCIES)

—pre

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

(environment variable: PIP_PRE)

-e, —editable <path/url>

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

(environment variable: PIP_EDITABLE)

—dry-run

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

(environment variable: PIP_DRY_RUN)

-t, —target <dir>

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.

(environment variable: PIP_TARGET)

—platform <platform>

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.

(environment variable: PIP_PLATFORM)

—python-version <python_version>

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

(environment variable: PIP_PYTHON_VERSION)

—implementation <implementation>

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.

(environment variable: PIP_IMPLEMENTATION)

—abi <abi>

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.

(environment variable: PIP_ABI)

—user

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

(environment variable: PIP_USER)

—root <dir>

Install everything relative to this alternate root directory.

(environment variable: PIP_ROOT)

—prefix <dir>

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.

(environment variable: PIP_PREFIX)

—src <dir>

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

(environment variable: PIP_SRC, PIP_SOURCE, PIP_SOURCE_DIR, PIP_SOURCE_DIRECTORY)

-U, —upgrade

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

(environment variable: PIP_UPGRADE)

—upgrade-strategy <upgrade_strategy>

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

(environment variable: PIP_UPGRADE_STRATEGY)

—force-reinstall

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

(environment variable: PIP_FORCE_REINSTALL)

-I, —ignore-installed

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!

(environment variable: PIP_IGNORE_INSTALLED)

—ignore-requires-python

Ignore the Requires-Python information.

(environment variable: PIP_IGNORE_REQUIRES_PYTHON)

—no-build-isolation

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

(environment variable: PIP_NO_BUILD_ISOLATION)

—use-pep517

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

(environment variable: PIP_USE_PEP517)

—check-build-dependencies

Check the build dependencies when PEP517 is used.

(environment variable: PIP_CHECK_BUILD_DEPENDENCIES)

—break-system-packages

Allow pip to modify an EXTERNALLY-MANAGED Python installation

(environment variable: PIP_BREAK_SYSTEM_PACKAGES)

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

(environment variable: PIP_CONFIG_SETTINGS)

—global-option <options>

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

(environment variable: PIP_GLOBAL_OPTION)

—compile

Compile Python source files to bytecode

(environment variable: PIP_COMPILE)

—no-compile

Do not compile Python source files to bytecode

(environment variable: PIP_NO_COMPILE)

—no-warn-script-location

Do not warn when installing scripts outside PATH

(environment variable: PIP_NO_WARN_SCRIPT_LOCATION)

—no-warn-conflicts

Do not warn about broken dependencies

(environment variable: PIP_NO_WARN_CONFLICTS)

—no-binary <format_control>

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.

(environment variable: PIP_NO_BINARY)

—only-binary <format_control>

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.

(environment variable: PIP_ONLY_BINARY)

—prefer-binary

Prefer binary packages over source packages, even if the source packages are newer.

(environment variable: PIP_PREFER_BINARY)

—require-hashes

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.

(environment variable: PIP_REQUIRE_HASHES)

—progress-bar <progress_bar>

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

(environment variable: PIP_PROGRESS_BAR)

—root-user-action <root_user_action>

Action if pip is run as a root user [warn, ignore] (default: warn)

(environment variable: PIP_ROOT_USER_ACTION)

—report <file>

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.

(environment variable: PIP_REPORT)

—group <[path:]group>

Install a named dependency-group from a “pyproject.toml” file. If a path is given, the name of the file must be “pyproject.toml”. Defaults to using “pyproject.toml” in the current directory.

(environment variable: PIP_GROUP)

—no-clean

Don’t clean up build directories.

(environment variable: PIP_NO_CLEAN)

-i, —index-url <url>

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.

(environment variable: PIP_INDEX_URL, PIP_PYPI_URL)

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

(environment variable: PIP_EXTRA_INDEX_URL)

—no-index

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

(environment variable: PIP_NO_INDEX)

-f, —find-links <url>

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.

(environment variable: PIP_FIND_LINKS)

Examples¶

  1. Install SomePackage and its dependencies from PyPI using Requirement Specifiers

    Unix/macOS

    python -m pip install SomePackage            # latest version
    python -m pip install 'SomePackage==1.0.4'   # specific version
    python -m pip install 'SomePackage>=1.0.4'   # minimum version
    

    Windows

    py -m pip install SomePackage            # latest version
    py -m pip install "SomePackage==1.0.4"   # specific version
    py -m pip install "SomePackage>=1.0.4"   # minimum version
    
  2. Install a list of requirements specified in a file. See the Requirements files.

    Unix/macOS

    python -m pip install -r requirements.txt
    

    Windows

    py -m pip install -r requirements.txt
    
  3. Upgrade an already installed SomePackage to the latest from PyPI.

    Unix/macOS

    python -m pip install --upgrade SomePackage
    

    Windows

    py -m pip install --upgrade SomePackage
    

    Note

    This will guarantee an update to SomePackage as it is a direct
    requirement, and possibly upgrade dependencies if their installed
    versions do not meet the minimum requirements of SomePackage.
    Any non-requisite updates of its dependencies (indirect requirements)
    will be affected by the --upgrade-strategy command.

  4. Install a local project in “editable” mode. See the section on Editable Installs.

    Unix/macOS

    python -m pip install -e .                # project in current directory
    python -m pip install -e path/to/project  # project in another directory
    

    Windows

    py -m pip install -e .                 # project in current directory
    py -m pip install -e path/to/project   # project in another directory
    
  5. Install a project from VCS

    Unix/macOS

    python -m pip install 'SomeProject@git+https://git.repo/some_pkg.git@1.3.1'
    

    Windows

    py -m pip install "SomeProject@git+https://git.repo/some_pkg.git@1.3.1"
    
  6. Install a project from VCS in “editable” mode. See the sections on VCS Support and Editable Installs.

    Unix/macOS

    python -m pip install -e 'git+https://git.repo/some_pkg.git#egg=SomePackage'          # from git
    python -m pip install -e 'hg+https://hg.repo/some_pkg.git#egg=SomePackage'            # from mercurial
    python -m pip install -e 'svn+svn://svn.repo/some_pkg/trunk/#egg=SomePackage'         # from svn
    python -m pip install -e 'git+https://git.repo/some_pkg.git@feature#egg=SomePackage'  # from 'feature' branch
    python -m pip install -e 'git+https://git.repo/some_repo.git#egg=subdir&subdirectory=subdir_path' # install a python package from a repo subdirectory
    

    Windows

    py -m pip install -e "git+https://git.repo/some_pkg.git#egg=SomePackage"          # from git
    py -m pip install -e "hg+https://hg.repo/some_pkg.git#egg=SomePackage"            # from mercurial
    py -m pip install -e "svn+svn://svn.repo/some_pkg/trunk/#egg=SomePackage"         # from svn
    py -m pip install -e "git+https://git.repo/some_pkg.git@feature#egg=SomePackage"  # from 'feature' branch
    py -m pip install -e "git+https://git.repo/some_repo.git#egg=subdir&subdirectory=subdir_path" # install a python package from a repo subdirectory
    
  7. Install a package with extras, i.e., optional dependencies
    (specification).

    Unix/macOS

    python -m pip install 'SomePackage[PDF]'
    python -m pip install 'SomePackage[PDF] @ git+https://git.repo/SomePackage@main#subdirectory=subdir_path'
    python -m pip install '.[PDF]'  # project in current directory
    python -m pip install 'SomePackage[PDF]==3.0'
    python -m pip install 'SomePackage[PDF,EPUB]'  # multiple extras
    

    Windows

    py -m pip install "SomePackage[PDF]"
    py -m pip install "SomePackage[PDF] @ git+https://git.repo/SomePackage@main#subdirectory=subdir_path"
    py -m pip install ".[PDF]"  # project in current directory
    py -m pip install "SomePackage[PDF]==3.0"
    py -m pip install "SomePackage[PDF,EPUB]"  # multiple extras
    
  8. Install a particular source archive file.

    Unix/macOS

    python -m pip install './downloads/SomePackage-1.0.4.tar.gz'
    python -m pip install 'http://my.package.repo/SomePackage-1.0.4.zip'
    

    Windows

    py -m pip install "./downloads/SomePackage-1.0.4.tar.gz"
    py -m pip install "http://my.package.repo/SomePackage-1.0.4.zip"
    
  9. Install a particular source archive file following direct references
    (specification).

    Unix/macOS

    python -m pip install 'SomeProject@http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl'
    python -m pip install 'SomeProject @ http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl'
    python -m pip install 'SomeProject@http://my.package.repo/1.2.3.tar.gz'
    

    Windows

    py -m pip install "SomeProject@http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl"
    py -m pip install "SomeProject @ http://my.package.repo/SomeProject-1.2.3-py33-none-any.whl"
    py -m pip install "SomeProject@http://my.package.repo/1.2.3.tar.gz"
    
  10. Install from alternative package repositories.

    Install from a different index, and not PyPI

    Unix/macOS

    python -m pip install --index-url http://my.package.repo/simple/ SomePackage
    

    Windows

    py -m pip install --index-url http://my.package.repo/simple/ SomePackage
    

    Install from a local flat directory containing archives (and don’t scan indexes):

    Unix/macOS

    python -m pip install --no-index --find-links=file:///local/dir/ SomePackage
    python -m pip install --no-index --find-links=/local/dir/ SomePackage
    python -m pip install --no-index --find-links=relative/dir/ SomePackage
    

    Windows

    py -m pip install --no-index --find-links=file:///local/dir/ SomePackage
    py -m pip install --no-index --find-links=/local/dir/ SomePackage
    py -m pip install --no-index --find-links=relative/dir/ SomePackage
    

    Search an additional index during install, in addition to PyPI

    Warning

    Using this option to search for packages which are not in the main
    repository (such as private packages) is unsafe, per a security
    vulnerability called
    dependency confusion:
    an attacker can claim the package on the public repository in a way that
    will ensure it gets chosen over the private package.

    Unix/macOS

    python -m pip install --extra-index-url http://my.package.repo/simple SomePackage
    

    Windows

    py -m pip install --extra-index-url http://my.package.repo/simple SomePackage
    
  11. Find pre-release and development versions, in addition to stable versions. By default, pip only finds stable versions.

    Unix/macOS

    python -m pip install --pre SomePackage
    

    Windows

    py -m pip install --pre SomePackage
    
  12. Install packages from source.

    Do not use any binary packages

    Unix/macOS

    python -m pip install SomePackage1 SomePackage2 --no-binary :all:
    

    Windows

    py -m pip install SomePackage1 SomePackage2 --no-binary :all:
    

    Specify SomePackage1 to be installed from source:

    Unix/macOS

    python -m pip install SomePackage1 SomePackage2 --no-binary SomePackage1
    

    Windows

    py -m pip install SomePackage1 SomePackage2 --no-binary SomePackage1
    

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Введение в управление зависимостями в Python

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

Кинга Идем в IT: пошаговый план для смены профессии

Почему важно управлять зависимостями?

Управление зависимостями помогает избежать конфликтов между различными версиями библиотек. Например, если одна библиотека требует версию numpy 1.18, а другая — 1.19, это может вызвать проблемы. Правильное управление зависимостями позволяет вам точно указать, какие версии библиотек необходимы для вашего проекта, и избежать подобных конфликтов. Это также облегчает процесс развертывания проекта на новых машинах или серверах, так как все необходимые библиотеки будут установлены автоматически.

Создание и использование файла requirements.txt

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

Создание файла requirements.txt

Чтобы создать файл requirements.txt, выполните следующую команду в терминале:

Эта команда сохранит все текущие установленные пакеты и их версии в файл requirements.txt. Пример содержимого файла может выглядеть так:

Ручное редактирование файла requirements.txt

Вы также можете вручную добавить или изменить зависимости в файле requirements.txt. Например, если вам нужно добавить библиотеку pandas, просто добавьте строку:

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

Установка зависимостей из файла requirements.txt

После того как файл requirements.txt создан, вы можете установить все зависимости, указанные в нем, с помощью одной команды:

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

Проверка установленных зависимостей

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

Эта команда выведет список всех установленных библиотек и их версий. Это полезно для проверки того, что все зависимости были установлены корректно.

Обновление и удаление зависимостей

Обновление зависимостей

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

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

Удаление зависимостей

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

Например, чтобы удалить библиотеку requests, выполните:

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

Советы и лучшие практики

Использование виртуальных окружений

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

Активируйте виртуальное окружение:

  • На Windows:

  • На macOS и Linux:

Преимущества виртуальных окружений

Использование виртуальных окружений имеет несколько преимуществ. Во-первых, это позволяет избежать конфликтов между различными проектами, которые могут требовать разные версии одних и тех же библиотек. Во-вторых, это облегчает управление зависимостями и делает ваш проект более переносимым.

Регулярное обновление файла requirements.txt

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

Использование точных версий

Указывайте точные версии библиотек в файле requirements.txt. Это поможет избежать неожиданных изменений в поведении вашего проекта при обновлении библиотек. Например:

Проверка совместимости

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

Документация и комментарии

Добавляйте комментарии в файл requirements.txt, чтобы объяснить, почему была выбрана та или иная версия библиотеки. Это поможет другим разработчикам (и вам самим в будущем) понять логику выбора версий.

Автоматизация управления зависимостями

Для автоматизации управления зависимостями можно использовать инструменты, такие как pip-tools или poetry. Эти инструменты позволяют автоматически генерировать файл requirements.txt и управлять зависимостями более эффективно.

Заключение

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

Читайте также

Last Updated :
24 Nov, 2023

Python package is a container for storing multiple Python modules. We can install packages in Python using the pip package manager. In this article, we will learn to install multiple packages at once using the requirements.txt file. We will use the pip install requirements.txt command to install Python packages. The requirements.txt file is useful to install all packages at once for a project, it is easy to hand over to other developers and we can use this to install different versions of packages for different Python projects.

The classic way of installing packages in Python using pip:

pip install package_name1, package_name2

Installing Python Packages using requirements.txt file

Here, we will see how to install Python packages using pip install requirements.txt. We will define each package in a new line in the requirements.txt file.

Let’s say below the three Python packages we defined in the requirements.txt file.

  • Pandas
  • Pillow
  • Numpy

We will install packages using the below command. Run the below command where the requirements.txt file is present.

pip install -r requirements.txt

PIP will download and install all packages present in that file.

This section covers the basics of how to install Python packages.

It’s important to note that the term “package” in this context is being used to
describe a bundle of software to be installed (i.e. as a synonym for a
distribution). It does not refer to the kind
of package that you import in your Python source code
(i.e. a container of modules). It is common in the Python community to refer to
a distribution using the term “package”. Using
the term “distribution” is often not preferred, because it can easily be
confused with a Linux distribution, or another larger software distribution
like Python itself.

Requirements for Installing Packages¶

This section describes the steps to follow before installing other Python
packages.

Ensure you can run Python from the command line¶

Before you go any further, make sure you have Python and that the expected
version is available from your command line. You can check this by running:

You should get some output like Python 3.6.3. If you do not have Python,
please install the latest 3.x version from python.org or refer to the
Installing Python section of the Hitchhiker’s Guide to Python.

Note

If you’re a newcomer and you get an error like this:

>>> python3 --version
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python3' is not defined

It’s because this command and other suggested commands in this tutorial
are intended to be run in a shell (also called a terminal or
console). See the Python for Beginners getting started tutorial for
an introduction to using your operating system’s shell and interacting with
Python.

Note

If you’re using an enhanced shell like IPython or the Jupyter
notebook, you can run system commands like those in this tutorial by
prefacing them with a ! character:

In [1]: import sys
        !{sys.executable} --version
Python 3.6.3

It’s recommended to write {sys.executable} rather than plain python in
order to ensure that commands are run in the Python installation matching
the currently running notebook (which may not be the same Python
installation that the python command refers to).

Note

Due to the way most Linux distributions are handling the Python 3
migration, Linux users using the system Python without creating a virtual
environment first should replace the python command in this tutorial
with python3 and the python -m pip command with python3 -m pip --user. Do not
run any of the commands in this tutorial with sudo: if you get a
permissions error, come back to the section on creating virtual environments,
set one up, and then continue with the tutorial as written.

Ensure you can run pip from the command line¶

Additionally, you’ll need to make sure you have pip available. You can
check this by running:

If you installed Python from source, with an installer from python.org, or
via Homebrew you should already have pip. If you’re on Linux and installed
using your OS package manager, you may have to install pip separately, see
Installing pip/setuptools/wheel with Linux Package Managers.

If pip isn’t already installed, then first try to bootstrap it from the
standard library:

Unix/macOS

python3 -m ensurepip --default-pip

Windows

py -m ensurepip --default-pip

If that still doesn’t allow you to run python -m pip:

  • Securely Download get-pip.py [1]

  • Run python get-pip.py. [2] This will install or upgrade pip.
    Additionally, it will install Setuptools and wheel if they’re
    not installed already.

    Warning

    Be cautious if you’re using a Python install that’s managed by your
    operating system or another package manager. get-pip.py does not
    coordinate with those tools, and may leave your system in an
    inconsistent state. You can use python get-pip.py --prefix=/usr/local/
    to install in /usr/local which is designed for locally-installed
    software.

Ensure pip, setuptools, and wheel are up to date¶

While pip alone is sufficient to install from pre-built binary archives,
up to date copies of the setuptools and wheel projects are useful
to ensure you can also install from source archives:

Unix/macOS

python3 -m pip install --upgrade pip setuptools wheel

Windows

py -m pip install --upgrade pip setuptools wheel

Optionally, create a virtual environment¶

See section below for details,
but here’s the basic venv [3] command to use on a typical Linux system:

Unix/macOS

python3 -m venv tutorial_env
source tutorial_env/bin/activate

Windows

py -m venv tutorial_env
tutorial_env\Scripts\activate

This will create a new virtual environment in the tutorial_env subdirectory,
and configure the current shell to use it as the default python environment.

Creating Virtual Environments¶

Python “Virtual Environments” allow Python packages to be installed in an isolated location for a particular application,
rather than being installed globally. If you are looking to safely install
global command line tools,
see Installing stand alone command line tools.

Imagine you have an application that needs version 1 of LibFoo, but another
application requires version 2. How can you use both these applications? If you
install everything into /usr/lib/python3.6/site-packages (or whatever your
platform’s standard location is), it’s easy to end up in a situation where you
unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be?
If an application works, any change in its libraries or the versions of those
libraries can break the application.

Also, what if you can’t install packages into the
global site-packages directory? For instance, on a shared host.

In all these cases, virtual environments can help you. They have their own
installation directories and they don’t share libraries with other virtual
environments.

Currently, there are two common tools for creating Python virtual environments:

  • venv is available by default in Python 3.3 and later, and installs
    pip into created virtual environments in Python 3.4 and later
    (Python versions prior to 3.12 also installed Setuptools).

  • virtualenv needs to be installed separately, but supports Python 2.7+
    and Python 3.3+, and pip, Setuptools and wheel are
    installed into created virtual environments by default. Note that setuptools is no longer
    included by default starting with Python 3.12 (and virtualenv follows this behavior).

The basic usage is like so:

Using venv:

Unix/macOS

python3 -m venv <DIR>
source <DIR>/bin/activate

Windows

py -m venv <DIR>
<DIR>\Scripts\activate

Using virtualenv:

Unix/macOS

python3 -m virtualenv <DIR>
source <DIR>/bin/activate

Windows

virtualenv <DIR>
<DIR>\Scripts\activate

For more information, see the venv docs or
the virtualenv docs.

The use of source under Unix shells ensures
that the virtual environment’s variables are set within the current
shell, and not in a subprocess (which then disappears, having no
useful effect).

In both of the above cases, Windows users should not use the
source command, but should rather run the activate
script directly from the command shell like so:

Managing multiple virtual environments directly can become tedious, so the
dependency management tutorial introduces a
higher level tool, Pipenv, that automatically manages a separate
virtual environment for each project and application that you work on.

Use pip for Installing¶

pip is the recommended installer. Below, we’ll cover the most common
usage scenarios. For more detail, see the pip docs,
which includes a complete Reference Guide.

Installing from PyPI¶

The most common usage of pip is to install from the Python Package
Index
using a requirement specifier. Generally speaking, a requirement specifier is
composed of a project name followed by an optional version specifier. A full description of the supported specifiers can be
found in the Version specifier specification.
Below are some examples.

To install the latest version of “SomeProject”:

Unix/macOS

python3 -m pip install "SomeProject"

Windows

py -m pip install "SomeProject"

To install a specific version:

Unix/macOS

python3 -m pip install "SomeProject==1.4"

Windows

py -m pip install "SomeProject==1.4"

To install greater than or equal to one version and less than another:

Unix/macOS

python3 -m pip install "SomeProject>=1,<2"

Windows

py -m pip install "SomeProject>=1,<2"

To install a version that’s compatible
with a certain version: [4]

Unix/macOS

python3 -m pip install "SomeProject~=1.4.2"

Windows

py -m pip install "SomeProject~=1.4.2"

In this case, this means to install any version “==1.4.*” version that’s also
“>=1.4.2”.

Source Distributions vs Wheels¶

pip can install from either Source Distributions (sdist) or Wheels, but if both are present
on PyPI, pip will prefer a compatible wheel. You can override
pip`s default behavior by e.g. using its –no-binary option.

Wheels are a pre-built distribution format that provides faster installation compared to Source
Distributions (sdist)
, especially when a
project contains compiled extensions.

If pip does not find a wheel to install, it will locally build a wheel
and cache it for future installs, instead of rebuilding the source distribution
in the future.

Upgrading packages¶

Upgrade an already installed SomeProject to the latest from PyPI.

Unix/macOS

python3 -m pip install --upgrade SomeProject

Windows

py -m pip install --upgrade SomeProject

Installing to the User Site¶

To install packages that are isolated to the
current user, use the --user flag:

Unix/macOS

python3 -m pip install --user SomeProject

Windows

py -m pip install --user SomeProject

For more information see the User Installs section
from the pip docs.

Note that the --user flag has no effect when inside a virtual environment
— all installation commands will affect the virtual environment.

If SomeProject defines any command-line scripts or console entry points,
--user will cause them to be installed inside the user base’s binary
directory, which may or may not already be present in your shell’s
PATH. (Starting in version 10, pip displays a warning when
installing any scripts to a directory outside PATH.) If the scripts
are not available in your shell after installation, you’ll need to add the
directory to your PATH:

  • On Linux and macOS you can find the user base binary directory by running
    python -m site --user-base and adding bin to the end. For example,
    this will typically print ~/.local (with ~ expanded to the absolute
    path to your home directory) so you’ll need to add ~/.local/bin to your
    PATH. You can set your PATH permanently by modifying ~/.profile.

  • On Windows you can find the user base binary directory by running py -m
    site --user-site
    and replacing site-packages with Scripts. For
    example, this could return
    C:\Users\Username\AppData\Roaming\Python36\site-packages so you would
    need to set your PATH to include
    C:\Users\Username\AppData\Roaming\Python36\Scripts. You can set your user
    PATH permanently in the Control Panel. You may need to log out for the
    PATH changes to take effect.

Requirements files¶

Install a list of requirements specified in a Requirements File.

Unix/macOS

python3 -m pip install -r requirements.txt

Windows

py -m pip install -r requirements.txt

Installing from VCS¶

Install a project from VCS in “editable” mode. For a full breakdown of the
syntax, see pip’s section on VCS Support.

Unix/macOS

python3 -m pip install -e SomeProject @ git+https://git.repo/some_pkg.git          # from git
python3 -m pip install -e SomeProject @ hg+https://hg.repo/some_pkg                # from mercurial
python3 -m pip install -e SomeProject @ svn+svn://svn.repo/some_pkg/trunk/         # from svn
python3 -m pip install -e SomeProject @ git+https://git.repo/some_pkg.git@feature  # from a branch

Windows

py -m pip install -e SomeProject @ git+https://git.repo/some_pkg.git          # from git
py -m pip install -e SomeProject @ hg+https://hg.repo/some_pkg                # from mercurial
py -m pip install -e SomeProject @ svn+svn://svn.repo/some_pkg/trunk/         # from svn
py -m pip install -e SomeProject @ git+https://git.repo/some_pkg.git@feature  # from a branch

Installing from other Indexes¶

Install from an alternate index

Unix/macOS

python3 -m pip install --index-url http://my.package.repo/simple/ SomeProject

Windows

py -m pip install --index-url http://my.package.repo/simple/ SomeProject

Search an additional index during install, in addition to PyPI

Unix/macOS

python3 -m pip install --extra-index-url http://my.package.repo/simple SomeProject

Windows

py -m pip install --extra-index-url http://my.package.repo/simple SomeProject

Installing from a local src tree¶

Installing from local src in
Development Mode,
i.e. in such a way that the project appears to be installed, but yet is
still editable from the src tree.

Unix/macOS

python3 -m pip install -e <path>

Windows

py -m pip install -e <path>

You can also install normally from src

Unix/macOS

python3 -m pip install <path>

Windows

Installing from local archives¶

Install a particular source archive file.

Unix/macOS

python3 -m pip install ./downloads/SomeProject-1.0.4.tar.gz

Windows

py -m pip install ./downloads/SomeProject-1.0.4.tar.gz

Install from a local directory containing archives (and don’t check PyPI)

Unix/macOS

python3 -m pip install --no-index --find-links=file:///local/dir/ SomeProject
python3 -m pip install --no-index --find-links=/local/dir/ SomeProject
python3 -m pip install --no-index --find-links=relative/dir/ SomeProject

Windows

py -m pip install --no-index --find-links=file:///local/dir/ SomeProject
py -m pip install --no-index --find-links=/local/dir/ SomeProject
py -m pip install --no-index --find-links=relative/dir/ SomeProject

Installing from other sources¶

To install from other data sources (for example Amazon S3 storage)
you can create a helper application that presents the data
in a format compliant with the simple repository API:,
and use the --extra-index-url flag to direct pip to use that index.

./s3helper --port=7777
python -m pip install --extra-index-url http://localhost:7777 SomeProject

Installing Prereleases¶

Find pre-release and development versions, in addition to stable versions. By
default, pip only finds stable versions.

Unix/macOS

python3 -m pip install --pre SomeProject

Windows

py -m pip install --pre SomeProject

Python Requirements.txt – How to Create and Pip Install Requirements.txt in Python

There are many Python packages we use to solve our coding problems daily. Take, for instance, the library «Beautiful Soup,» – it doesn’t come with Python by default and needs to be installed separately.

Many projects rely on libraries and other dependencies, and installing each one can be tedious and time-consuming.

This is where a ‘requirements.txt’ file comes into play. requirements.txt is a file that contains a list of packages or libraries needed to work on a project that can all be installed with the file. It provides a consistent environment and makes collaboration easier.

Format of a requirements.txt File

Image

Diagram showing a box containing requirements.txt and another box below it containing the text «package_name == version»

The above image shows a sample of a created requirements.txt file, containing a list of packages and versions of the installation.

Key Terms

I’ve mentioned a few terms so far that you may not know. Here’s what they mean, along with some other important terms you’ll come across when working with requirements.txt:

  • Dependencies are software components that a program needs to run correctly. They can be libraries, frameworks, or other programs.

  • Packages are a way to group together related dependencies. They make it easier to install and manage dependencies.

  • Virtual Environments is a directory that contains a copy of the Python interpreter and all of the packages that are required for a particular project.

  • Pip: This is a package manager for Python. You can use Pip to install, uninstall, and manage Python packages.

To create a requirements file, you must set up your virtual environment. If you use Pycharm, there’s a virtual environment already setup (.venv). But with Visual Studio code, you have to create the virtual environment yourself.

You can use your terminal or command prompt to create your requirements file. These are the steps to follow when creating the file:

First, open your terminal or command prompt. Then check to see if the file path shown is your working directory. Use the following command to do that:

$ cd folder-name #cd - change directory

In the command above, replace ‘folder-name’ with the directory name you want to access.

Image

Diagram showing set project directory on command line

Next, run this command:

$ pip freeze > requirements.txt

And you’ll see that the requirements file gets added

Here’s the output:

Image

Diagram showing the newly created requirements file

And here’s your newly created requirements.txt file:

Image

Diagram showing lists of packages in requirements file

The image above shows the dependencies you can work with along with their versions.

How to Work with a requirements.txt File

Now that we have the requirements file, you can see that it consists of a long list of different packages.

To work with the packages, you have to install them. You can do this by using the command prompt or terminal.

Type this command:

pip install -r requirements.txt

It will look like this:

Image

Image showing installation of packages present in requirements.txt file

Now that all the dependencies are installed, you can work with requirements.txt.

Example of using requirements.txt

In this example, we will be working with two libraries, beautifulsoup4 and requests, to return some information from a site.

Image

Diagram showing the working libraries for this example in the requirements file

In the image above, we see that the two libraries are present in the requirements.txt file and their version. Now we can work with the libraries because we installed them previously.

  • Import the library BeautifulSoup from the package name bs4 (beautifulsoup4) and also import the library requests.
from bs4 import BeautifulSoup
import requests
  • To fetch information from the website URL, we use the .get() method to tap into the requests library.
web_data = requests.get("https://www.lithuania.travel/en/category/what-is-lithuania", headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"})
  • Now that we have access to the the URL, the Beautiful Soup library accepts the web_data and returns all HTML contents present in it.
soup = BeautifulSoup(web_data.content, features="html.parser")
  • The final result I chose to return is elements with the

    tag in the first position [0].

news_info = soup.findAll("p")[0]
print(news_info.text

Bringing it all together:

from bs4 import BeautifulSoup
import requests
web_data = requests.get("https://www.lithuania.travel/en/category/what-is-lithuania", headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"})
soup = BeautifulSoup(web_data.content, features="html.parser")
news_info = soup.findAll("p")[0]
print(news_info.text)

And here’s the output:

Image

Diagram showing code and result

Benefits of Using a requirements.txt File

  • Managing dependencies: By listing the dependencies of your project in a requirements.txt file, you can easily see what packages are required and what versions they need to be.

  • Sharing your project with others: If you share your project with others, you can include the requirements.txt file so that they can easily install the required packages. This can save them time and frustration and can help to ensure that everyone is using the same versions of the packages.

Conclusion

In the article, we learned how to create a requirements.txt file and outlined the benefits of using it.

You should also try it out and work on a few projects with it. If you have any questions, you can reach out to me on Twitter 💙.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Настройка zoiper на windows
  • Как посмотреть критические ошибки windows 10
  • Как запустить skype на windows
  • Как включить центр обновления windows 10 через командную строку
  • Adblock для microsoft edge windows 11