note.nkmk.me

How to install Python packages with pip and requirements.txt

Posted: 2019-09-20 / Tags: Python, pip

If you are managing Python packages (libraries) with pip, you can use the configuration file requirements.txt to install the specified packages with the specified version.

This article describes the following contents.

  • Install packages with pip: -r requirements.txt
  • How to write configuration file requirements.txt
  • Export current environment configuration file: pip freeze

For basic information on how to use pip, such as installing, updating, and uninstalling packages, please see the following article.

Sponsored Link

Install packages with pip: -r requirements.txt

The following command will install the packages according to the configuration file requirements.txt.

$ pip install -r requirements.txt

You can name the configuration file whatever you like, but requirements.txt is often used.

Put requirements.txt in the directory where the command will be executed. If it is in another directory, specify its path like path/to/requirements.txt.

How to write configuration file "requirements.txt"

An example of configuration file requirements.txt is as follows.

###### Requirements without Version Specifiers ######
nose
nose-cov
beautifulsoup4

###### Requirements with 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.*

Like Python code, you can write comments using #.

You can specify the version with ==, >, >=, <, <=, etc. If the version is omitted, the latest version is installed.

Two conditions can be specified 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
Sponsored Link

Export current environment configuration file: pip freeze

pip freeze outputs the package and its version installed in the current environment in the form of a configuration file that can be used with pip install -r.

$ pip freeze
agate==1.6.0
agate-dbf==0.2.0
agate-excel==0.2.1
agate-sql==0.5.2

If you output pip freeze to a file with redirect >, you can use that file to install packages of the same version as the original environment in another environment.

First, output requirements.txt to a file.

$ pip freeze > requirements.txt

Copy or move this requirements.txt to another environment and install with it.

$ pip install -r requirements.txt
Sponsored Link
Share

Related Categories

Related Articles