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 usage of pip
, including how to install, update, and uninstall packages, see the following article.
Install packages with pip
and requirements.txt
The following command installs multiple packages at once based on a configuration file, typically named requirements.txt
. In some environments, you may need to use pip3
instead of pip
.
$ pip install -r requirements.txt
You can name the configuration file 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, such as path/to/requirements.txt
.
How to write requirements.txt
An example of a requirements.txt
file is shown below.
###### 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 package versions using operators like ==,
>
, >=
, <
, and <=
. If you omit the version specifier, the latest version will be installed.
Two conditions can be combined with AND by separating them with a comma. In the following example, a version >= 1.0
and <= 2.0
will be installed.
package >= 1.0, <= 2.0
Refer to the official documentation for detailed specifications.
- Requirements File Format - pip documentation v25.1
- Requirement Specifiers - pip documentation v25.1
- Version specifiers - Python Packaging User Guide
Create requirements.txt
with pip freeze
pip freeze
outputs a list of the packages installed in the current environment along with their versions, 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
...
You can use the redirection operator (>
) to save the pip freeze
output to a file. This file can be used to install the same package versions in a different environment.
First, redirect the pip freeze
output to a file named requirements.txt
.
$ pip freeze > requirements.txt
Next, copy or move this requirements.txt
file 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.