How to install Python packages with pip and requirements.txt
This article explains how to install Python packages using pip
and requirements.txt
.
For basic information on how to use pip
, such as installing, updating, and uninstalling packages, see the following article.
Install packages with pip
and requirements.txt
The following command installs packages in bulk according to the configuration file, requirements.txt
. In some environments, use pip3
instead of pip
.
$ pip install -r requirements.txt
The configuration file can be named arbitrarily, though requirements.txt
is commonly used.
Place requirements.txt
in the directory where you plan to run the command. If the file is in a different directory, specify its path, for example, path/to/requirements.txt
.
How to write requirements.txt
An example of requirements.txt
is as follows.
###### Requirements without Version Specifiers ######
nose
nose-cov
beautifulsoup4
#
###### Requirements with Version Specifiers ######
# See https://www.python.org/dev/peps/pep-0440/#version-specifiers
docopt == 0.6.1 # Version Matching. Must be version 0.6.1
keyring >= 4.1.1 # Minimum version 4.1.1
coverage != 3.5 # Version Exclusion. Anything except version 3.5
Mopidy-Dirble ~= 1.1 # Compatible release. Same as >= 1.1, == 1.*
As with Python code, comments can be included in requirements.txt
using #
.
You can specify the version of a package using ==
, >
, >=
, <
, <=
, and so on. Omitting the version specifier installs the latest version.
Two conditions can be combined with AND by separating them with a comma. In the following example, a version of 1.0
or later and 2.0
or earlier (1.0 <= ver <= 2.0
) is installed.
package >= 1.0, <= 2.0
Refer to the official documentation for detailed specifications.
- Requirements File Format - pip documentation v24.1
- Requirement Specifiers - pip documentation v24.1
- Version specifiers - Python Packaging User Guide
Create requirements.txt
with pip freeze
pip freeze
outputs the packages and their versions installed in the current environment in a format that can be used as requirements.txt
.
$ pip freeze
agate==1.6.0
agate-dbf==0.2.0
agate-excel==0.2.1
agate-sql==0.5.2
...
Using the redirection operator >
, you can save the output of pip freeze
to a file. This file can be used to install the same versions of packages in a different environment.
First, redirect the output of pip freeze
to a file named requirements.txt
.
$ pip freeze > requirements.txt
Next, copy or move this requirements.txt
to a different environment and use it to install the packages.
$ pip install -r requirements.txt
By following these steps, you can easily replicate the exact package setup from one environment to another.