12. Virtual Environments and Packages¶
Python applications will often use packages and modules that don’t come as part of the standard library. Applications will sometimes need a specific version of a library, because the application may require that a particular bug has been fixed or the application may be written using an obsolete version of the library’s interface.
This means it may not be possible for one Python installation to meet the requirements of every application. If application A needs version 1.0 of a particular module but application B needs version 2.0, then the requirements are in conflict and installing either version 1.0 or 2.0 will leave one application unable to run.
The solution for this problem is to create a virtual environment , a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.
Different applications can then use different virtual environments. To resolve the earlier example of conflicting requirements, application A can have its own virtual environment with version 1.0 installed while application B has another virtual environment with version 2.0. If application B requires a library be upgraded to version 3.0, this will not affect application A’s environment.
12.2. Creating Virtual Environments¶
The module used to create and manage virtual environments is called venv . venv will usually install the most recent version of Python that you have available. If you have multiple versions of Python on your system, you can select a specific Python version by running python3 or whichever version you want.
To create a virtual environment, decide upon a directory where you want to place it, and run the venv module as a script with the directory path:
This will create the tutorial-env directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter and various supporting files.
A common directory location for a virtual environment is .venv . This name keeps the directory typically hidden in your shell and thus out of the way while giving it a name that explains why the directory exists. It also prevents clashing with .env environment variable definition files that some tooling supports.
Once you’ve created a virtual environment, you may activate it.
On Unix or MacOS, run:
(This script is written for the bash shell. If you use the csh or fish shells, there are alternate activate.csh and activate.fish scripts you should use instead.)
Activating the virtual environment will change your shell’s prompt to show what virtual environment you’re using, and modify the environment so that running python will get you that particular version and installation of Python. For example:
To deactivate a virtual environment, type:
into the terminal.
12.3. Managing Packages with pip¶
You can install, upgrade, and remove packages using a program called pip. By default pip will install packages from the Python Package Index. You can browse the Python Package Index by going to it in your web browser.
pip has a number of subcommands: “install”, “uninstall”, “freeze”, etc. (Consult the Installing Python Modules guide for complete documentation for pip .)
You can install the latest version of a package by specifying a package’s name:
You can also install a specific version of a package by giving the package name followed by == and the version number:
If you re-run this command, pip will notice that the requested version is already installed and do nothing. You can supply a different version number to get that version, or you can run python -m pip install —upgrade to upgrade the package to the latest version:
python -m pip uninstall followed by one or more package names will remove the packages from the virtual environment.
python -m pip show will display information about a particular package:
python -m pip list will display all of the packages installed in the virtual environment:
python -m pip freeze will produce a similar list of the installed packages, but the output uses the format that python -m pip install expects. A common convention is to put this list in a requirements.txt file:
The requirements.txt can then be committed to version control and shipped as part of an application. Users can then install all the necessary packages with install -r :
pip has many more options. Consult the Installing Python Modules guide for complete documentation for pip . When you’ve written a package and want to make it available on the Python Package Index, consult the Distributing Python Modules guide.
Python Pipreqs — How to Create requirements.txt File Like a Sane Person
Every Python project should have a requirements.txt file. It stores the information of all libraries needed for a project to run, and is essential when deploying Python projects. This is traditionally done via the pip freeze command, which outputs all libraries installed in a virtual environment.
But what if you want only the ones used in the project? That’s where pipreqs comes into play. It does the same thing as pip freeze , but better.
Picture this — you create a new virtual environment and install a bunch of dependencies. During the project, you decide not to use some libraries, but you forget to delete them from the environment. A requirements.txt file generated with pip freeze will include both used and unused libraries, which is just a waste of resources.
There’s a better way, and today you’ll learn all about it.
Don’t feel like reading? Well, you don’t have to:
How to Use Python Pipreqs to Create requirements.txt File
Let’s get to it. I’ve created a new virtual environment with Anaconda called pipreqs_test based on Python 3.10. You’re free to use Anaconda or any other environment manager:
From here, let’s install a bunch of Python libraries with pip:
Here’s the shell output:

Image 1 — Installing Python libraries with pip (image by author)
And now, create a Python script that only uses Numpy and Pandas:
I’ve named mine script.py :

Image 2 — Contents of a Python file (image by author)
Let’s first see what issuing a pip freeze command will save into the requirements file:
As it turns out, a whole lot of libraries — both used and unused with their dependencies:

Image 3 — Requirements file generated with pip freeze (image by author)
If you were to run this script on a new machine and install Python dependencies from a requirements.txt file, many unused libraries would get installed. It would be better if you could somehow install only the libraries that were used in the project.
That’s where pipreqs shines. But first, we have to install it:
Pipreqs works by scanning all .py files in a given directory and looking for the imports in Python files. This way, it should write only the libraries you actually use to requirements.txt .
Here’s the general command for saving requirements:
If you’re in a Python project folder, simply run this command:
You’ll see the following output:

Image 4 — Using pipreqs to create requirements.txt file (image by author)
The dependencies are now saved to requirements.txt , so let’s see what’s inside:

Image 5 — Requirements file generated with pipreqs (image by author)
Amazing — only Numpy and Pandas were included! These are all the dependencies you need to run the project on a new machine or a new environment.
But is that all you can do with Pipreqs? Let’s go over a couple of “advanced” use cases next.
What Else Can You Do With Pipreqs?
You can just check which libraries are used in the project by printing them to the console:
Here are the results:

Image 6 — Print dependencies (image by author)
This won’t write the dependencies to a file, so keep that in mind.
You can also force overwrite the requirements.txt file. This command is needed if you already have the requirements file present, as running pipreqs . alone won’t overwrite it:
The updated requirements.txt file is now saved:

Image 7 — Force overwrite requirements.txt file (image by author)
You can also save the requirements.txt file to a different destination. Just make sure to include the full file path including the file name:
Here’s how I saved the file to the Desktop:

Image 8 — Saving requirements.txt to a different location (image by author)
And that’s pretty much all you can do with Pipreqs. There are some additional options and parameters, but these are the ones you’ll use 99% of the time.
Let’s make a short recap next.
Summing up Python Pipreqs
There’s nothing wrong with generating requirements files the old way via pip freeze . It just includes a bunch of unnecessary libraries and their dependencies, as everything installed in an environment (or God forbid, globally) gets picked.
Pipreqs solves this inconvenience by scanning Python files in a given project folder and looking for libraries that were actually imported. It’s not something groundbreaking, but it will make your projects tidier, which is always welcome.
What do you use to kee track of project dependencies? Do you see Pipreqs as a better alternative? Let me know in the comment section below.
User Guide#
pip is a command line program. When you install pip, a pip command is added to your system, which can be run from the command prompt as follows:
python -m pip executes pip using the Python interpreter you specified as python. So /usr/bin/python3.7 -m pip means you are executing pip for your interpreter located at /usr/bin/python3.7 .
py -m pip executes pip using the latest Python interpreter you have installed. For more details, read the Python Windows launcher docs.
Installing Packages#
pip supports installing from PyPI, version control, local projects, and directly from distribution files.
The most common scenario is to install from PyPI using Requirement Specifiers
For more information and examples, see the pip install reference.
Basic Authentication Credentials
This is now covered in Authentication .
This is now covered in Authentication .
This is now covered in Authentication .
Using a Proxy Server#
When installing packages from PyPI, pip requires internet access, which in many corporate environments requires an outbound HTTP proxy server.
pip can be configured to connect through a proxy server in various ways:
using the —proxy command-line option to specify a proxy in the form scheme://[user:passwd@]proxy.server:port
by setting the standard environment-variables http_proxy , https_proxy and no_proxy .
using the environment variable PIP_USER_AGENT_USER_DATA to include a JSON-encoded string in the user-agent variable used in pip’s requests.
Requirements Files#
“Requirements files” are files containing a list of items to be installed using pip install like so:
Details on the format of the files are here: Requirements File Format .
Logically, a Requirements file is just a list of pip install arguments placed in a file. Note that you should not rely on the items in the file being installed by pip in any particular order.
Requirements files can also be served via a URL, e.g. http://example.com/requirements.txt besides as local files, so that they can be stored and served in a centralized place.
In practice, there are 4 common uses of Requirements files:
Requirements files are used to hold the result from pip freeze for the purpose of achieving Repeatable Installs . In this case, your requirement file contains a pinned version of everything that was installed when pip freeze was run.
Requirements files are used to force pip to properly resolve dependencies. pip 20.2 and earlier doesn’t have true dependency resolution, but instead simply uses the first specification it finds for a project. E.g. if pkg1 requires pkg3>=1.0 and pkg2 requires pkg3>=1.0,<=2.0 , and if pkg1 is resolved first, pip will only use pkg3>=1.0 , and could easily end up installing a version of pkg3 that conflicts with the needs of pkg2 . To solve this problem, you can place pkg3>=1.0,<=2.0 (i.e. the correct specification) into your requirements file directly along with the other top level requirements. Like so:
Requirements files are used to force pip to install an alternate version of a sub-dependency. For example, suppose ProjectA in your requirements file requires ProjectB , but the latest version (v1.3) has a bug, you can force pip to accept earlier versions like so:
Requirements files are used to override a dependency with a local patch that lives in version control. For example, suppose a dependency SomeDependency from PyPI has a bug, and you can’t wait for an upstream fix. You could clone/copy the src, make the fix, and place it in VCS with the tag sometag . You’d reference it in your requirements file with a line like so:
If SomeDependency was previously a top-level requirement in your requirements file, then replace that line with the new line. If SomeDependency is a sub-dependency, then add the new line.
It’s important to be clear that pip determines package dependencies using install_requires metadata, not by discovering requirements.txt files embedded in projects.
Constraints Files#
Constraints files are requirements files that only control which version of a requirement is installed, not whether it is installed or not. Their syntax and contents is a subset of Requirements Files , with several kinds of syntax not allowed: constraints must have a name, they cannot be editable, and they cannot specify extras. In terms of semantics, there is one key difference: Including a package in a constraints file does not trigger installation of the package.
Use a constraints file like so:
Constraints files are used for exactly the same reason as requirements files when you don’t know exactly what things you want to install. For instance, say that the “helloworld” package doesn’t work in your environment, so you have a local patched version. Some things you install depend on “helloworld”, and some don’t.
One way to ensure that the patched version is used consistently is to manually audit the dependencies of everything you install, and if “helloworld” is present, write a requirements file to use when installing that thing.
Constraints files offer a better way: write a single constraints file for your organisation and use that everywhere. If the thing being installed requires “helloworld” to be installed, your fixed version specified in your constraints file will be used.
Constraints file support was added in pip 7.1. In Changes to the pip dependency resolver in 20.3 (2020) we did a fairly comprehensive overhaul, removing several undocumented and unsupported quirks from the previous implementation, and stripped constraints files down to being purely a way to specify global (version) limits for packages.
Same as requirements files, constraints files can also be served via a URL, e.g. http://example.com/constraints.txt, so that your organization can store and serve them in a centralized place.
Installing from Wheels#
“Wheel” is a built, archive format that can greatly speed installation compared to building and installing from source archives. For more information, see the Wheel docs , PEP 427, and PEP 425.
pip prefers Wheels where they are available. To disable this, use the —no-binary flag for pip install .
If no satisfactory wheels are found, pip will default to finding source archives.
To install directly from a wheel archive:
To include optional dependencies provided in the provides_extras metadata in the wheel, you must add quotes around the install target name:
In the future, the path[extras] syntax may become deprecated. It is recommended to use PEP 508 syntax wherever possible.
For the cases where wheels are not available, pip offers pip wheel as a convenience, to build wheels for all your requirements and dependencies.
pip wheel requires the wheel package to be installed, which provides the “bdist_wheel” setuptools extension that it uses.
To build wheels for your requirements and all their dependencies to a local directory:
And then to install those requirements just using your local directory of wheels (and not from PyPI):
Uninstalling Packages#
pip is able to uninstall most packages like so:
pip also performs an automatic uninstall of an old version of a package before upgrading to a newer version.
For more information and examples, see the pip uninstall reference.
Listing Packages#
To list installed packages:
To list outdated packages, and show the latest version available:
To show details about an installed package:
For more information and examples, see the pip list and pip show reference pages.
Searching for Packages#
pip can search PyPI for packages using the pip search command:
The query will be used to search the names and summaries of all packages.
For more information and examples, see the pip search reference.
This is now covered in Configuration .
This is now covered in Configuration .
This is now covered in Configuration .
This is now covered in Configuration .
Command Completion#
pip comes with support for command line completion in bash, zsh and fish.
To setup for bash:
To setup for zsh:
To setup for fish:
To setup for powershell:
Alternatively, you can use the result of the completion command directly with the eval function of your shell, e.g. by adding the following to your startup file:
Installing from local packages#
In some cases, you may want to install from local packages only, with no traffic to PyPI.
First, download the archives that fulfill your requirements:
Note that pip download will look in your wheel cache first, before trying to download from PyPI. If you’ve never installed your requirements before, you won’t have a wheel cache for those items. In that case, if some of your requirements don’t come as wheels from PyPI, and you want wheels, then run this instead:
Then, to install from local only, you’ll be using —find-links and —no-index like so:
“Only if needed” Recursive Upgrade#
pip install —upgrade now has a —upgrade-strategy option which controls how pip handles upgrading of dependencies. There are 2 upgrade strategies supported:
eager : upgrades all dependencies regardless of whether they still satisfy the new parent requirements
only-if-needed : upgrades a dependency only if it does not satisfy the new parent requirements
The default strategy is only-if-needed . This was changed in pip 10.0 due to the breaking nature of eager when upgrading conflicting dependencies.
It is important to note that —upgrade affects direct requirements (e.g. those specified on the command-line or via a requirements file) while —upgrade-strategy affects indirect requirements (dependencies of direct requirements).
As an example, say SomePackage has a dependency, SomeDependency , and both of them are already installed but are not the latest available versions:
pip install SomePackage : will not upgrade the existing SomePackage or SomeDependency .
pip install —upgrade SomePackage : will upgrade SomePackage , but not SomeDependency (unless a minimum requirement is not met).
pip install —upgrade SomePackage —upgrade-strategy=eager : upgrades both SomePackage and SomeDependency .
As an historic note, an earlier “fix” for getting the only-if-needed behaviour was:
A proposal for an upgrade-all command is being considered as a safer alternative to the behaviour of eager upgrading.
User Installs#
With Python 2.6 came the “user scheme” for installation, which means that all Python distributions support an alternative install location that is specific to a user. The default location for each OS is explained in the python documentation for the site.USER_BASE variable. This mode of installation can be turned on by specifying the —user option to pip install .
Moreover, the “user scheme” can be customized by setting the PYTHONUSERBASE environment variable, which updates the value of site.USER_BASE .
To install “SomePackage” into an environment with site.USER_BASE customized to ‘/myappenv’, do the following:
pip install —user follows four rules:
When globally installed packages are on the python path, and they conflict with the installation requirements, they are ignored, and not uninstalled.
When globally installed packages are on the python path, and they satisfy the installation requirements, pip does nothing, and reports that requirement is satisfied (similar to how global packages can satisfy requirements when installing packages in a —system-site-packages virtualenv).
pip will not perform a —user install in a —no-site-packages virtualenv (i.e. the default kind of virtualenv), due to the user site not being on the python path. The installation would be pointless.
In a —system-site-packages virtualenv, pip will not install a package that conflicts with a package in the virtualenv site-packages. The —user installation would lack sys.path precedence and be pointless.
To make the rules clearer, here are some examples:
From within a —no-site-packages virtualenv (i.e. the default kind):
From within a —system-site-packages virtualenv where SomePackage==0.3 is already installed in the virtualenv:
From within a real python, where SomePackage is not installed globally:
From within a real python, where SomePackage is installed globally, but is not the latest version:
From within a real python, where SomePackage is installed globally, and is the latest version:
This is now covered in Repeatable Installs .
Fixing conflicting dependencies
Using pip from your program#
As noted previously, pip is a command line program. While it is implemented in Python, and so is available from your Python code via import pip , you must not use pip’s internal APIs in this way. There are a number of reasons for this:
The pip code assumes that it is in sole control of the global state of the program. pip manages things like the logging system configuration, or the values of the standard IO streams, without considering the possibility that user code might be affected.
pip’s code is not thread safe. If you were to run pip in a thread, there is no guarantee that either your code or pip’s would work as you expect.
pip assumes that once it has finished its work, the process will terminate. It doesn’t need to handle the possibility that other code will continue to run after that point, so (for example) calling pip twice in the same process is likely to have issues.
This does not mean that the pip developers are opposed in principle to the idea that pip could be used as a library — it’s just that this isn’t how it was written, and it would be a lot of work to redesign the internals for use as a library, handling all of the above issues, and designing a usable, robust and stable API that we could guarantee would remain available across multiple releases of pip. And we simply don’t currently have the resources to even consider such a task.
What this means in practice is that everything inside of pip is considered an implementation detail. Even the fact that the import name is pip is subject to change without notice. While we do try not to break things as much as possible, all the internal APIs can change at any time, for any reason. It also means that we generally won’t fix issues that are a result of using pip in an unsupported way.
It should also be noted that installing packages into sys.path in a running Python process is something that should only be done with care. The import system caches certain data, and installing new packages while a program is running may not always behave as expected. In practice, there is rarely an issue, but it is something to be aware of.
Having said all of the above, it is worth covering the options available if you decide that you do want to run pip from within your program. The most reliable approach, and the one that is fully supported, is to run pip in a subprocess. This is easily done using the standard subprocess module:
If you want to process the output further, use one of the other APIs in the module. We are using freeze here which outputs installed packages in requirements format.:
If you don’t want to use pip’s command line functionality, but are rather trying to implement code that works with Python packages, their metadata, or PyPI, then you should consider other, supported, packages that offer this type of ability. Some examples that you could consider include:
packaging — Utilities to work with standard package metadata (versions, requirements, etc.)
setuptools (specifically pkg_resources ) — Functions for querying what packages the user has installed on their system.
distlib — Packaging and distribution utilities (including functions for interacting with PyPI).
Changes to the pip dependency resolver in 20.3 (2020)#
pip 20.3 has a new dependency resolver, on by default for Python 3 users. (pip 20.1 and 20.2 included pre-release versions of the new dependency resolver, hidden behind optional user flags.) Read below for a migration guide, how to invoke the legacy resolver, and the deprecation timeline. We also made a two-minute video explanation you can watch.
We will continue to improve the pip dependency resolver in response to testers’ feedback. Please give us feedback through the resolver testing survey.
Watch out for#
The big change in this release is to the pip dependency resolver within pip.
Computers need to know the right order to install pieces of software (“to install x , you need to install y first”). So, when Python programmers share software as packages, they have to precisely describe those installation prerequisites, and pip needs to navigate tricky situations where it’s getting conflicting instructions. This new dependency resolver will make pip better at handling that tricky logic, and make pip easier for you to use and troubleshoot.
The most significant changes to the resolver are:
It will reduce inconsistency: it will no longer install a combination of packages that is mutually inconsistent. In older versions of pip, it is possible for pip to install a package which does not satisfy the declared requirements of another installed package. For example, in pip 20.0, pip install "six<1.12" "virtualenv==20.0.2" does the wrong thing, “successfully” installing six==1.11 , even though virtualenv==20.0.2 requires six>=1.12.0,<2 (defined here). The new resolver, instead, outright rejects installing anything if it gets that input.
It will be stricter — if you ask pip to install two packages with incompatible requirements, it will refuse (rather than installing a broken combination, like it did in previous versions).
So, if you have been using workarounds to force pip to deal with incompatible or inconsistent requirements combinations, now’s a good time to fix the underlying problem in the packages, because pip will be stricter from here on out.
This also means that, when you run a pip install command, pip only considers the packages you are installing in that command, and may break already-installed packages. It will not guarantee that your environment will be consistent all the time. If you pip install x and then pip install y , it’s possible that the version of y you get will be different than it would be if you had run pip install x y in a single command. We are considering changing this behavior (per #7744) and would like your thoughts on what pip’s behavior should be; please answer our survey on upgrades that create conflicts.
We are also changing our support for Constraints Files , editable installs, and related functionality. We did a fairly comprehensive overhaul and stripped constraints files down to being purely a way to specify global (version) limits for packages, and so some combinations that used to be allowed will now cause errors. Specifically:
Constraints don’t override the existing requirements; they simply constrain what versions are visible as input to the resolver (see #9020)
Providing an editable requirement ( -e . ) does not cause pip to ignore version specifiers or constraints (see #8076), and if you have a conflict between a pinned requirement and a local directory then pip will indicate that it cannot find a version satisfying both (see #8307)
Hash-checking mode requires that all requirements are specified as a == match on a version and may not work well in combination with constraints (see #9020 and #8792)
If necessary to satisfy constraints, pip will happily reinstall packages, upgrading or downgrading, without needing any additional command-line options (see #8115 and Options that control the installation process )
Unnamed requirements are not allowed as constraints (see #6628 and #8210)
Links are not allowed as constraints (see #8253)
Constraints cannot have extras (see #6628)
Per our Python 2 Support policy, pip 20.3 users who are using Python 2 will use the legacy resolver by default. Python 2 users should upgrade to Python 3 as soon as possible, since in pip 21.0 in January 2021, pip dropped support for Python 2 altogether.
How to upgrade and migrate#
Install pip 20.3 with python -m pip install —upgrade pip .
Validate your current environment by running pip check . This will report if you have any inconsistencies in your set of installed packages. Having a clean installation will make it much less likely that you will hit issues with the new resolver (and may address hidden problems in your current environment!). If you run pip check and run into stuff you can’t figure out, please ask for help in our issue tracker or chat.
Test the new version of pip.
While we have tried to make sure that pip’s test suite covers as many cases as we can, we are very aware that there are people using pip with many different workflows and build processes, and we will not be able to cover all of those without your help.
If you use pip to install your software, try out the new resolver and let us know if it works for you with pip install . Try:
installing several packages simultaneously
re-creating an environment using a requirements.txt file
using pip install —force-reinstall to check whether it does what you think it should
using constraints files
the “Setups to test with special attention” and “Examples to try” below
If you have a build pipeline that depends on pip installing your dependencies for you, check that the new resolver does what you need.
Run your project’s CI (test suite, build process, etc.) using the new resolver, and let us know of any issues.
If you have encountered resolver issues with pip in the past, check whether the new resolver fixes them, and read Dealing with dependency conflicts . Also, let us know if the new resolver has issues with any workarounds you put in to address the current resolver’s limitations. We’ll need to ensure that people can transition off such workarounds smoothly.
If you develop or support a tool that wraps pip or uses it to deliver part of your functionality, please test your integration with pip 20.3.
Troubleshoot and try these workarounds if necessary.
If pip is taking longer to install packages, read Dependency resolution backtracking for ways to reduce the time pip spends backtracking due to dependency conflicts.
If you don’t want pip to actually resolve dependencies, use the —no-deps option. This is useful when you have a set of package versions that work together in reality, even though their metadata says that they conflict. For guidance on a long-term fix, read Dealing with dependency conflicts .
If you run into resolution errors and need a workaround while you’re fixing their root causes, you can choose the old resolver behavior using the flag —use-deprecated=legacy-resolver . This will work until we release pip 21.0 (see Deprecation timeline ).
Please report bugs through the resolver testing survey.
Setups to test with special attention#
Requirements files with 100+ packages
Installation workflows that involve multiple requirements files
Requirements files that include hashes ( Hash-checking Mode ) or pinned dependencies (perhaps as output from pip-compile within pip-tools )
Файл requirements.txt в Python и как его создать
Файл requirements.txt — это список всех модулей и пакетов Python, которые нужны для полноценной работы вашей программы. Его использование позволяет легко отслеживать весь перечень нужных компонентов, избавляя пользователей от необходимости их ручного поиска и установки.
В данном материале мы расскажем вам о том, как создать файл requirements.txt , а также о его преимуществах и особенностях использования.
Преимущества использования файла зависимостей
-
Возможность отслеживать актуальный список всех модулей и пакетов Python, используемых в вашем проекте. Облегчение процесса установки недостающих компонентов. Удобство совместной работы. Если на ПК другого пользователя отсутствуют нужные модули, они будут быстро загружены из файла requirements.txt , обеспечив беспроблемный запуск программы. Если вы захотите удалить, добавить или обновить модуль, изменения будет достаточно внести только в файл requirements.txt . При загрузке requirements.txt , GitHub проверяет зависимости на наличие конфликтов, и в некоторых случаях устраняет уязвимости.
Как создать файл зависимостей
Для этого вам достаточно перейти в корневой каталог проекта, где хранятся ваши .py -файлы, и создать текстовый документ requirements.txt . Важно убедиться, чтобы название было именно таким.
Также этот файл может быть сгенерирован автоматически с помощью следующей команды:
pip freeze > requirements.txt
Она возвращает список всех установленных модулей с указанием версий и помещает их в текстовый файл. Обратите внимание, что pip freeze подразумевает использование виртуальной среды для текущего проекта. В противном случае, список зависимостей может включать в себя и те пакеты, которые установлены в другие виртуальные среды.
Дополнительный вариант использования этой команды, который возвращает только локальные установленные пакеты:
pip freeze —local
Добавление модулей в файл
После создания файла его необходимо заполнить названиями модулей и их версиями. Самый простой способ — сделать это вручную. Вот пример содержимого requirements.txt :
Перечислив все зависимости, сохраняем файл и закрываем его.
Второй способ — команда pip freeze > requirements.txt , которая работает, даже если файл уже существует. Его пустое содержимое будет заполнено списком пакетов так же, как и при генерации нового файла.
Установка модулей из файла
Для того чтобы установить пакеты из requirements.txt , необходимо открыть командную строку, перейти в каталог проекта и ввести следующую команду:
pip install -r requirements.txt
Если вы хотите обновить компоненты вместо их повторной установки, используйте команду pip install -U -r requirements.txt .
Как поддерживать requirements.txt в актуальном состоянии
Если вы уже создали файл с зависимостями ранее, но по какой-то причине не обновляли его содержимое, волноваться не стоит. Выполните следующие шаги:
-
Выведите список устаревших модулей с помощью pip list —outdated . Обновите выведенные пакеты вручную с помощью pip install -U PackageName или автоматически, используя pip install -U -r requirements.txt . Убедитесь, что ваша программа работает корректно. Используйте pip freeze > requirements.txt , чтобы актуализировать содержимое файла с необходимыми внешними зависимостями.
Таким образом вы сможете без проблем обновить информацию об используемых установленных пакетах, даже если в течение определенного времени не занимались управлением зависимостями.
Помните, что постоянное обновление файла requirements.txt помогает избежать многих проблем, связанных с устаревшими или отсутствующими модулями или пакетами. Как следствие, вы обеспечите корректную работу всех ваших сборок на любых ПК.
Как еще можно создать файл зависимостей?
Можно воспользоваться библиотекой pipreqs , которая сделает все за нас. Её запуск в командной строке сгенерирует файл с зависимостями:
При этом никто не запрещает вновь обратиться к pip freeze или заполнению документа вручную.