I’m still relatively new to Python, and especially new to package management in Python. As I continue to learn, I’ve been trying to share helpful information I come across. My most recent challenge was figuring out how to install only the packages from the requirements file that aren’t already installed.
To install only the packages from requirements.txt that are not already installed, you can use the
pip install command with the
-r option and the
--upgrade-strategy only-if-needed option:
pip install -r requirements.txt --upgrade-strategy only-if-needed
-r option tells
pip to install the packages listed in the specified file (in this case, requirements.txt). The
--upgrade-strategy only-if-needed option tells
pip to only upgrade a package if it is required by the specified package versions in requirements.txt. This means that pip will not upgrade packages that are already installed and at the correct version.
For example, if requirements.txt contains the following package specifications:
In our scenario,
some-old-package version 1.0 is already installed, but
awesome-new-package is not yet installed. Running the above
pip command will only install
awesome-new-package version 2.0, and not upgrade
It’s worth reading (or re-reading) the documentation page for the pip install command; it’s a pretty quick read and not as long as you might imagine.