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 usepython 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 thatsetuptools
is no longer
included by default starting with Python 3.12 (andvirtualenv
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 addingbin
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 yourPATH
permanently by modifying ~/.profile. -
On Windows you can find the user base binary directory by running
py -m
and replacing
site --user-sitesite-packages
withScripts
. For
example, this could return
C:\Users\Username\AppData\Roaming\Python36\site-packages
so you would
need to set yourPATH
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
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:
-
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
pyproject.toml
orsetup.py
,
otherwise pip will report an error). -
Local file (a sdist or wheel format archive, following the naming
conventions for those formats). -
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:
-
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
usinginstall_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.
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¶
-
Install
SomePackage
and its dependencies from PyPI using Requirement SpecifiersUnix/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
-
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
-
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 ofSomePackage
.
Any non-requisite updates of its dependencies (indirect requirements)
will be affected by the--upgrade-strategy
command. -
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
-
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"
-
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
-
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
-
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"
-
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"
-
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
-
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
-
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
Чтобы не писать нужные функции с нуля каждый раз, разработчики используют библиотеки. Это наборы готового кода для выполнения какой-то задачи — например, математическая библиотека numpy содержит функции для работы с числами.
Большинство библиотек не подключены к языку программирования по умолчанию. Их нужно загружать отдельно. Разберемся, как сделать это в Python — одном из самых популярных языков программирования.
Способ №1. Установить библиотеку вручную
Большинство пакетов с библиотеками Python собрано на сайте под названием PyPI. На его главной странице есть окно поиска, через которое можно найти интересующий пакет. А затем открыть его страницу и увидеть информацию по нему.
Сайт предлагает скачать и установить любой пакет двумя способами:
- с помощью команды пакетного менеджера pip;
- вручную — для этого нужно скачать архив с библиотекой с сайта PyPI.
После того как файл загрузится на компьютер, его нужно будет разархивировать. А затем — открыть консоль командной строки и перейти в папку, где лежит пакет. Там в терминале нужно будет выполнить команду:
python setup.py install
Эта команда с помощью Python запускает файл setup.py — в пакете он отвечает за установку компонентов.
Если возникает ошибка — скорее всего дело в том, что командная строка не понимает, где находится Python. В таком случае можно прописать полный путь к папке, где находятся файлы языка.
Способ №2. Использовать easy install
Для Python существует модуль под названием easy install. Он позволяет быстро устанавливать в язык новые расширения — понадобится всего лишь написать одну команду. Скачать этот модуль проще всего вместе с расширением setuptools — оно есть на PyPI, и его можно установить вручную способом из предыдущего пункта.
После того как утилита установится, можно будет загрузить библиотеку в Python через нее. Для этого нужно из папки, где установлен setuptools, вызвать в терминале команду:
easy_install <имя пакета>
Вместо <имя пакета> нужно подставить название интересующей библиотеки, которое можно посмотреть на PyPI или ее официальном сайте. Инструмент скачает и установит библиотеку автоматически.
Пользоваться easy install можно и из других папок — но понадобится прописывать полный путь к утилите. Правда, если установить ее в корневой каталог операционной системы, это делать не понадобится — ОС будет «видеть» утилиту, из какой бы папки ее ни вызвали.
У easy install есть два ограничения:
- с ее помощью нельзя удалить какую-то библиотеку или отключить ее;
- иногда при использовании возникают ошибки — она может попытаться запустить не установленную на компьютер библиотеку.
Способ №3. Использовать pip
Это самый популярный способ установки библиотек в Python. Для языка существует менеджер пакетов под названием pip. С его помощью устанавливать новые компоненты можно буквально с помощью одной команды.
Начиная с Python версии 3.4 pip устанавливается вместе с самим языком. Его не нужно скачивать отдельно. Это понадобится, только если вы работаете с какой-то из более старых версий.
Проверить, установлен ли pip, можно с помощью команды в терминале:
pip --version
Если менеджер уже установлен, высветится его версия. Если нет — появится сообщение, что такого пакета в системе нет. В таком случае pip можно скачать с PyPI и установить ручным способом.
Также pip можно загрузить с сайта PyPa — рабочей группы, которая занимается его разработкой. Вручную это можно сделать в любой системе. В Linux также возможно скачать его с помощью команды в терминале:
wget https://bootstrap.pypa.io/get-pip.py
Или с помощью easy install:
easy_install pip
Оба способа позволяют скачать файл get-pip.py. После этого его нужно запустить в Python через терминал:
python get-pip.py
После того как pip загрузится и инсталлируется, его можно будет использовать для установки библиотек. Это просто — фактически установить нужный пакет можно с помощью одной команды. Но возможности pip куда шире, чем у easy install.
Менеджер умеет не только устанавливать, но и обновлять или удалять библиотеки в Python. А еще — подгружать зависимости, то есть модули, нужные для работы какой-то из библиотек.
Установить модуль в Python с помощью pip можно так:
pip install <имя пакета>
Кроме того, есть еще несколько команд, которые могут понадобиться при работе с библиотеками:
- pip install -U <имя пакета> — обновить библиотеку до актуальной версии;
- pip install <имя пакета>==<номер версии> — установить библиотеку какой-то конкретной версии;
- pip install —force-reinstall <имя пакета> — принудительно переустановить библиотеку, например если та установилась с ошибками;
- pip uninstall <имя пакета> — удалить библиотеку, которая перестала быть нужной;
- pip list — посмотреть список установленных пакетов;
- pip show <имя пакета> — посмотреть информацию о конкретном установленном пакете.
Достаточно ввести нужную команду в терминал, и pip автоматически выполнит нужное действие.
Что еще стоит сделать
Каким бы способом вы ни пользовались, после установки нужно проверить, точно ли пакет работает нормально. Для этого достаточно подключить библиотеку к Python-коду и попробовать ее использовать.
Чтобы конкретная программа «увидела» нужный модуль, его нужно добавить в код с помощью строчки:
import <имя пакета>
Обычно модули подключают в самом начале файла с кодом. То есть, первые строки программы — добавление библиотек, нужных для ее работы.
После этого можно использовать в коде нужные функции и компоненты из библиотеки. Если все установилось как следует, при этом не должно возникнуть никаких ошибок. Готово — нужными модулями можно пользоваться на свое усмотрение.
Последнее обновление: 08.03.2025
По умолчанию вместе с установкой интерпретатора Python также устанавливается множество дополнительных пакетов/библиотек, которые с помощью импорта соответствующих модулей мы можем использовать в своей программе. Часть из них уже была рассмотрена
в предыдущих статьях. Однако кроме встроенных пакетов есть огромнейшее количество пакетов, которые развиваются сообществом (различными компаниями или даже отдельными разработчиками) и которые мы также можем использовать при разработке приложения.
Для управления пакетами — их установки или удаления необходим такой инструмент как менеджер пакетов. Для работы с пакетами Python существует множество менеджеров пакетов, например,
pip, conda, pixi, uv и так далее.
Этой статье мы рассмотрим использование менеджера pip, поскольку он является стандартным и наиболее распространенным способом для управления пакетами, и, кроме того, обычно он устанавливается вместе с
интерпретатором Python и поэтому обычно уже присутствует в системе. pip загружает пакеты из репозитория PyPI (Python Package Index), который является самым большим репозиторием пакетов Python. Так, на момент написания текущей статьи PyPI насчитывал более 600000 проектов.
Репозиторий также доступен по адресу https://pypi.org/. В частности, через веб-интерфейс можно найти нужный пакет, всю связанную с ним информацию, его историю версий и т.д.
Для начала необходимо убедиться, что у вас установлен pip. Если у вас установлен Python, то, скорее всего, pip тоже уже есть. Чтобы проверить наличие pip, откройте терминал (или командную строку) и выполните команду:
pip --version
Если pip установлен, вы увидите версию менеджера пакетов:
eugene@Eugene:~$ pip --version pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12) eugene@Eugene:~$
Если pip по какой-то причине вдруг не был установлен, то мы увидим ошибку типа
"pip" не является внутренней или внешней командой, исполняемой программой или пакетным файлом
В этом случае нам надо установить pip. Для этого можно выполнить в командной строке/консоли следующую команду:
python -m ensurepip --upgrade
Если pip ранее уже был установлен, то можно его обновить с помощью команды
python -m pip install --upgrade pip
Установка виртуальной среды
В операционной системе на базе Linux (Ubuntu, Debian и др.), где используется встроенное управление пакетами, например, через apt или другой пакетный менеджер, перед установкой пакетов Python через pip
также необходимо создать виртуальную среду. На Windows использовать виртуальную среду необязательно, но тоже является рекомендуемым подходом при работы с пакетами Python.
Виртуальная среда позволяет изолировать пакеты от системных установок Python.
Так, без использования виртуальной среды все устанавливаемые через pip пакеты на Windows устанавливаются глобально. Однако что если после создания первого приложения выйдет новая версия используемого пакета?
Если мы захотим использовать для второго проекта новую версию пакета, то из-за глобальной установки пакетов придется обновлять первый проект, который использует старую версию.
Это потребует некоторой дополнительной работы по обновлению, так как не всегда соблюдается обратная совместимость между пакетами.
Если мы решим использовать для второго проекта старую версию, то мы лишимся потенциальных преимуществ новой версии.
И использование виртуальной среды как раз позволяет разграничить пакеты для каждого проекта.
Для работы с виртуальной средой в python применяется встроенный модуль venv. Обычно этот модуль доступен по умолчанию, но на некоторых операционных системах на базе Linux он может остутствовать.
В этом случае нам надо установить в ОС пакет python3-venv. Например, установка на Ubuntu/Debian:
sudo apt install python3-venv
Итак, создадим вируальную среду. Вначале определим каталог для проектов и перейдем в него в консоли/командной строке. Затем для создания виртуальной среды выполним следующую команду:
python3 -m venv myenv
Модулю venv передается название среды, которая в данном случае будет называться «myvenv». Для наименования виртуальных сред нет каких-то определенных условностей.
После этого в текущей папке будет создан подкаталог «myvenv».
eugene@Eugene:/python/metanit$ python3 -m venv myenv eugene@Eugene:/python/metanit$ ls -l myenv total 2 drwxrwxrwx 1 root root 528 Mar 8 14:56 bin drwxrwxrwx 1 root root 0 Mar 8 14:56 include drwxrwxrwx 1 root root 152 Mar 8 14:56 lib lrwxrwxrwx 1 root root 3 Mar 8 14:56 lib64 -> lib -rwxrwxrwx 1 root root 192 Mar 8 14:56 pyvenv.cfg eugene@Eugene:/eugene/python/metanit$
Активация виртуальной среды
Для использования виртуальную среду надо активировать. И каждый раз, когда мы будем работать с проектом, надо активировать связанную с ним виртуальную среду.
Например, активируем выше созданную среду, которая располагается в текущем каталоге в папке «myvenv». Процесс активации немного отличается в зависимости от операционной системы и от того, какие инструменты применяются. Так, в Windows можно использовать командную строку и PowerShell,
но между ними есть отличия:
-
Активация в Windows в коммандной строке
Если наша ОС — Windows, то в папке myvenv/Scripts/ мы можем найти файл activate.bat, который активирует
виртуальную среду. Так, в Windows активация виртуальной среды в коммандной строке будет выглядеть таким образом:myvenv\Scripts\activate.bat
-
Активация в Windows в PowerShell
Также при работе на Windows в папке myvenv/Scripts/ мы можем найти файлactivate.ps1, который также активирует виртуальную среду,
но применяется только в PowerShell. Но при работе с PowerShell следует учитывать, что по умолчанию в этой оболочке запрещено применять скрипты. Поэтому
перед активацией среды необходимо установить разрешения для текущего пользователя. Поэтому для активации виртуальной среды в PowerShell необходимо выполнить две следующих команды:Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser myvenv\Scripts\Activate.ps1
-
Активация в Linux и MacOS
Для Linux и MacOS активация будет производиться с помощью следующей команды:
source myvenv/bin/activate
После активации слева текущего пути мы увидим название виртуальной среду в круглых скобках:
(myenv) eugene@Eugene:/eugene/python/metanit$
Пример на основе командной строки Windows:
C:\eugene\python\metanit>python -m venv .venv C:\eugene\python\metanit>myvenv\Scripts\activate.bat (.venv) C:\eugene\python\metanit>
Пример на основе консоли Ubuntu:
eugene@Eugene:/python/metanit$ python3 -m venv myenv eugene@Eugene:/python/metanit$ source myenv/bin/activate (myenv) eugene@Eugene:/python/metanit$
Деактивация виртуальной среды
После окончания работы с виртуальной средой мы можем ее деактивировать с помощью команды:
deactivate
Управление пакетами с помощью pip
Установка пакетов
Для установки пакетов с помощью pip применяется команда
pip install название_пакета
Рассмотрим на примере установки популярного пакета для отрисовки графиков matplotlib. Для его установки после активации виртуальной среды (как было показано выше)
выполним команду
pip install matplotlib
И в конце проверим установку, выполнив команду, которая выводит версию matplotlib:
python -c "import matplotlib; print(matplotlib.__version__)"
Полный пример
(myenv) eugene@Eugene:/python/metanit$ pip install matplotlib Collecting matplotlib Downloading matplotlib-3.10.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (11 kB) Collecting contourpy>=1.0.1 (from matplotlib) Downloading contourpy-1.3.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (5.4 kB) Collecting cycler>=0.10 (from matplotlib) Downloading cycler-0.12.1-py3-none-any.whl.metadata (3.8 kB) ..................................................................... Downloading six-1.17.0-py2.py3-none-any.whl (11 kB) Installing collected packages: six, pyparsing, pillow, packaging, kiwisolver, fonttools, cycler, contourpy, python-dateutil, matplotlib Successfully installed contourpy-1.3.1 cycler-0.12.1 fonttools-4.56.0 kiwisolver-1.4.8 matplotlib-3.10.1 packaging-24.2 pillow-11.1.0 pyparsing-3.2.1 python-dateutil-2.9.0.post0 six-1.17.0 (myenv) eugene@Eugene:/python/metanit$ python -c "import matplotlib; print(matplotlib.__version__)" 3.10.1 (myenv) eugene@Eugene:/python/metanit$
Получение информации о пакетах
С помощью команды pip list можно получить список всех установленных пакетов и их версий:
(myenv) eugene@Eugene:/python/metanit$ pip list Package Version --------------- ----------- contourpy 1.3.1 cycler 0.12.1 fonttools 4.56.0 kiwisolver 1.4.8 matplotlib 3.10.1 packaging 24.2 pillow 11.1.0 pip 24.0 pyparsing 3.2.1 python-dateutil 2.9.0.post0 six 1.17.0 (myenv) eugene@Eugene:/python/metanit$
Как видно из консольного вывода, несмотря на то, что был установлен только один пакет, вместе с ним также был установлен набор других пакетов, от которых зависит основной пакет.
Если надо получить информацию по какому-то конкретному пакету, то можно использовать команду
pip show имя_пакета
Например, получим информацию по matplotlib:
(myenv) eugene@Eugene:/python/metanit$ pip show matplotlib Name: matplotlib Version: 3.10.1 Summary: Python plotting package Home-page: Author: John D. Hunter, Michael Droettboom ................................ Requires: contourpy, cycler, fonttools, kiwisolver, numpy, packaging, pillow, pyparsing, python-dateutil Required-by: (myenv) eugene@Eugene:/python/metanit$
Удаление пакета
Для удаления пакета применяется команда
pip uninstall имя_пакета
Использование установленных пакетов
Теперь для демонстрации применим установленный пакет в простейшей программе. Например, выведем показатели популярности языка Python согласно рейтингу TIOBE за 2022 год помесячно. Для этого в текущем каталоге определим файл app.py со следующим кодом:
import matplotlib.pyplot as plt # импортируем функциональность модуля pyplot из пакета matplotlib months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] rates = [13.58, 15.33, 14.26, 13.92, 12.74, 12.2, 13.44, 15.63, 15.74, 17.08, 17.18, 16.66] # метка по оси X plt.xlabel("month") # метка по оси Y plt.ylabel("rate") plt.plot(months, rates) plt.show()
Так как этот код приведен больше для демонстрации, то рассмотрим вкратце, что он делает. Здесь список months хранит сокращенные названия месяцев, а rates — показатели популярности.
С помощью функции xlabel()
устанавливаем метку для оси Х, а с помощью функции ylabel()
— для оси Y. В функцию plot()
передаются
два списка — для отображения по оси X (здесь список months) и по оси Y (здесь список rates). Функция plot() принимает набор значений, которые надо
вывести на графике. С помощью функции show()
отображаем график в окне просмотра по умолчанию.
После активации виртуальной среды (если она ранее была деактивирована или не была активирован) запустип скрипт на выполнение:
(myenv) eugene@Eugene:/python/metanit$ python3 app.py
В итоге нам отобразится следующее окно:
Таким образом, пакетный менеджер pip позволяет устанавливать пакеты Python. А создание виртуальных окружений предоставляет лучший способ работать с Python-проектами, особенно когда нужно установить дополнительные пакеты, такие как matplotlib, без изменения глобальных системных установок. Это изолирует зависимости и предотвращает конфликты с другими проектами и системными библиотеками.
Современные разработки требуют гибкости и адаптивности, особенно когда дело касается среды программирования на Windows. Часто программисты сталкиваются с необходимостью добавления функциональности, которая поможет достичь требуемого результата быстрее. Именно здесь на помощь приходят готовые модули. Их применение импонирует простотой и позволяет сосредоточиться на решении ключевых задач, а не на дебрях сложных настроек.
В процессе работы над проектами важную роль играет команда pip, являющаяся помощником в интеграции модулей в ваши проекты. С ее помощью вы можете без труда добавлять, обновлять и управлять компонентами, необходимыми для ваших приложений. Это особенно ценно, учитывая разнообразие операционной системы Windows и ее специфику.
Чтобы задействовать pip, убедитесь, что она правильно установлена и функционирует в вашей системе. Если вы не уверены, достаточно открыть командную строку и ввести следующую команду, чтобы проверить доступность tools:
pip --version
В случае, если командная строка не распознает pip, необходимо выполнить ее загрузку и настройку. Это станет надежным шагом на пути к эффективной работе с многочисленными расширениями, которые откроют для вас новые горизонты в разработке. Каждый новый модуль – это возможность сделать ваше приложение более многофункциональным и удобным для пользователей.
Переходя ко внедрению различных расширений, не забудьте, что важно читать документацию к каждому из них. Она даст ценную информацию о возможностях и специфике работы с расширениями. По мере усложнения задач, вы откроете для себя все больше инструментов, которые упростят вашу работу и добавят проекту новизны и мощности. Таким образом, используя простые команды, вы обладаете возможностью творить уникальные решения.
Подготовка рабочей среды Python
Перед началом эффективной работы с разнообразными инструментами и технологиями, важно правильно настроить виртуальную среду. Это создаст благоприятные условия для дальнейшего применения различных пакетов и библиотек.
Шаг 1: Установка интерпретатора
В первую очередь вам понадобятся программные компоненты для работы с языком. Например, загрузку и установку можно выполнить с официального сайта. Эта помощь обеспечит вас базовой необходимой средой для дальнейшего использования утилит и редакторов кода.
Шаг 2: Настройка переменных среды в Windows
После установки важно проверить, добавлен ли путь к месту, где установлен интерпретатор, в системные переменные. В Windows это гарантирует, что вы сможете запускать скрипты и команды из командной строки без указания полного пути. Откройте Панель управления > Система > Дополнительные параметры системы > Переменные среды. В разделе Системные переменные найдите переменную Path и добавьте путь к папке с интерпретатором.
Шаг 3: Работа с инструментом pip
Инструмент pip
является важной частью управления пакетами. Он поможет добавлять и обновлять библиотеки из единого репозитория. Перед началом убедитесь, что pip
обновлен до последней версии. Для этого в командной строке выполните команду:
python -m pip install --upgrade pip
Последовательно выполняя эти шаги, вы создадите устойчивую основу для применения и тестирования различных продуктов и библиотек, а также обеспечите гибкость и оперативность своих разработок.
Создание виртуального окружения
Работа с проектами, использующими различные версии пакетов, может стать сложной задачей. Возникает потребность в изолировании окружений, чтобы управлять зависимостями и предотвращать конфликты. Виртуальные окружения помогают решить эту проблему, обеспечивая независимость одного проекта от другого.
Первый шаг в создании виртуального окружения – установить инструмент venv, который доступен в комплекте с современными версиями системы. venv позволяет создавать локальные окружения для ваших проектов, что упрощает управление пакетами и их версиями.
На Windows откройте командную строку и выполните следующую команду, чтобы создать новое виртуальное окружение:
python -m venv myenv
В этой команде myenv
– это имя папки, в которую будет помещено окружение. Вы можете назвать его по-другому, если это необходимо. После создания вам потребуется активировать виртуальное окружение, прежде чем устанавливать зависимости через pip.
Чтобы активировать окружение на Windows, используйте команду:
myenv\Scripts\activate
После выполнения этих шагов ваш командный интерфейс будет работать в контексте виртуального окружения. Теперь вы можете управлять пакетами, используя pip без риска изменения глобальных настроек.
Для выхода из виртуального окружения введите команду:
deactivate
Виртуальные окружения являются важным инструментом для создания надежных и независимых рабочих сценариев, упрощая управление проектами и сокращая потенциальные проблемы с совместимостью пакетов и библиотек.
Поиск необходимой библиотеки
Прежде чем работать с проектом, зачастую требуется расширить его функционал с помощью различных пакетов. В данном разделе рассмотрим, как можно эффективно найти нужную библиотеку под ваши задачи и как убедиться в ее надежности и популярности. Этот процесс важен, чтобы избежать проблем в будущем.
Наиболее распространенным инструментом для работы с библиотеками является менеджер пакетов pip
, который позволяет быстро находить и загружать пакеты из открытых репозиториев. Чтобы выполнить поиск, можно воспользоваться командой:
pip search [название или ключевое слово]
Эта команда выдаст список пакетов, содержащих в своем описании указанное ключевое слово. Однако, стоит учитывать, что функция search
может быть неактивна в некоторых версиях pip
по умолчанию, и рекомендуется производить поиск на официальном сайте PyPI, где представлен огромный выбор пакетов с детальным описанием, инструкцией и количеством загрузок.
При необходимости вы можете получить дополнительную информацию о конкретном пакете, выполнив команду:
pip show [название пакета]
После выполнения команды, вы получите подробную информацию о версии, авторе, лицензии, а также ссылки на документацию и домашнюю страницу пакета.
При выборе библиотеки следует обращать внимание на следующие аспекты: как часто она обновляется, соответствует ли лицензия вашей задаче, и какая поддержка оказывается сообществом. Рекомендуется выбирать популярные и активно поддерживаемые пакеты, чтобы минимизировать риск столкнуться с неразрешенными ошибками и проблемами совместимости.
В дополнение, если ваш компьютер работает на Windows, убедитесь, что библиотека совместима с этой операционной системой. Это можно уточнить в документации пакета или на форуме разработчиков, где зачастую можно найти ответы на возникающие вопросы и помощь от более опытных пользователей.
Следуя этим рекомендациям, вы сможете грамотно выбирать нужные пакеты для своего проекта, будь то небольшой скрипт или крупное приложение, и создавать решения, которые удовлетворят даже самым сложным требованиям.
Использование pip для установки
Вот последовательный план действий:
- Убедитесь, что pip установлен в вашей системе. Обычно он идет в комплекте с последними версиями, но если вы работаете на Windows и не уверены в этом, проверьте, выполнив в командной строке:
- Если pip отсутствует, следуйте инструкциям на официальном сайте для установки.
- Получите небольшой список пакетов, которые вы хотите добавить в проект. Для поиска нужного пакета можно использовать команду:
pip search имя_пакета
После выбора нужного пакета, выполните команду для инсталляции:
pip install имя_пакета
Это позволит добавить пакет в рабочую среду. Если возникнут сложности, pip предоставит подробную информацию об ошибках, что поможет в их устранении.
- Для проверки успешности инсталляции используйте:
pip show имя_пакета
Эта команда отобразит информацию о версии, местоположении и других характеристиках пакета. В экстремальных случаях может потребоваться переустановка:
pip uninstall имя_пакета
pip install имя_пакета
Также полезно знать о возможностях обновления:
pip install --upgrade имя_пакета
Таким образом, pip предоставляет гибкие инструменты для управления пакетами, облегчая процесс добавления, обновления и удаления компонентов проекта.
Управление зависимостями и пакетами
При разработке проектов важно грамотно управлять зависимостями, чтобы избежать конфликтов и обеспечить стабильность работы. Современные инструменты предоставляют разнообразные возможности для эффективного управления пакетами, что позволяет вам сосредоточиться на разработке, не отвлекаясь на организационные моменты.
pip служит основным инструментом для работы с пакетами и их зависимостями. Однако, помимо базовых команд, таких как pip install
, он предлагает более функциональные возможности для продвинутого управления. Например, команда pip freeze
позволяет вывести список всех установленных пакетов с их версиями, что полезно для фиксации текущего состояния окружения.
Создание файла requirements.txt
с помощью команды pip freeze > requirements.txt
позволяет закрепить текущие версии и использовать их при развертывании проекта на других машинах. Установка всех пакетов из такого файла выполняется командой pip install -r requirements.txt
, что гарантирует соответствие всех зависимостей необходимой спецификации.
Для обновления установленных пакетов используется команда pip install --upgrade
, за которой следует имя пакета. Это может помочь в ситуации, когда необходимо получить последние исправления и улучшения, обеспечивая совместимость с новым функционалом.
При управлении множеством проектов рекомендуется организовать рабочее пространство таким образом, чтобы каждый проект был изолирован в своем виртуальном окружении. Это обеспечит независимость зависимостей и исключит конфликты между проектами.
Советы по устранению ошибок
При работе с пакетами и их конфигурацией могут возникать различные неисправности, мешающие корректной работе программ. Понимание того, как справляться с этими проблемами, позволит сэкономить время и успешно интегрировать необходимые пакеты в ваш проект. Ниже приведены методы, которые помогут эффективно диагностировать и исправлять возникающие ошибки.
Один из самых распространенных инструментов для работы с пакетами – это pip
. Однако, иногда команды pip
приводят к неожиданным ошибкам. Важно правильно интерпретировать сообщения об ошибках и искать их причины в соответствующей документации.
Иногда корректная работа pip
оказывается невозможной из-за конфликтующих версий пакета. Использование команды pip list
поможет увидеть перечень всех установленных пакетов и их версий. Если же найден конфликт, решите его, обновив или изменив необходимую версию с помощью команды pip install package-name==version
.
При обнаружении проблем с сетью следует проверять подключение к интернету. Используйте команду pip --proxy
, если требуется работа через прокси-сервер.
Для хранения информации об ошибках полезно вести журнал. Например, можно использовать команду pip install package-name --log log-file.txt
, чтобы записывать лог выполнения каждой команды.
Команда | Описание |
---|---|
pip list |
Показать перечень установленных пакетов с версиями |
pip install package-name==version |
Установить специфическую версию пакета |
pip --proxy |
Указать настройки прокси для работы в сети |
pip install package-name --log log-file.txt |
Создать лог ошибок и процесса выполнения |
Не забывайте обращаться за помощью к сообществу и к официальной документации, которая зачастую предоставляет решения для часто встречаемых проблем. Использование этих советов повысит вашу уверенность в решении возникающих неполадок и позволит идти в ногу с развивающимся проектом.
Комментарии