There are two ways of installing packages using pip, the most used Python package manager.
We can use pip to install packages inside our newly created environment. Pip is installed inside your virtual environment by default. Because everything is installed locally, you don’t need to become a superuser with
To install simplejson, simply use:
$ pip install simplejson
And to upgrade pip to the latest version, you can use pip too since it’s just another package inside your venv:
$ pip install --upgrade pip
In a virtual environment, it’s a good habit to install specific versions of packages. It ensures that you reap the full benefits of using virtual environments in the first place. After all, we do this to make sure our software always works as intended by pinning down specific dependency versions.
requirements.txt file contains a very simple list of dependencies, one per line. In its most simple form, it could look like this:
But what we really want is to pin the versions. That’s not hard either:
You can also relax these constraints a little, by using >= and <=, or even a combination of those:
How do you know what range to use? Unfortunately there are no rules to this. You will have to read the release notes and such from the package in question.
You can make your life a little easier by creating your requirements file using pip’s freeze option. First write your software and install all the requirements you need as you go with pip. Once you’re done, simply use the following command:
$ pip freeze > requirements.txt
Pip will create a requirements file with all the currently installed dependencies, including version numbers. Neat!
Finally, to install all the dependencies listed in this file, use:
pip install -r requirements.txt
If you liked this page, please share it with a fellow learner: