Install Packages from requirements.txt Using pip Only if They Aren’t Already Installed

Featured image for a blog post on using pip's upgrade-strategy flag.

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

The -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:

some-old-package==1.0
awesome-new-package==2.0

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 some-old-package.

Additional Reading

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.

About: Kurt Maine

Kurt Maine is a Full-Stack Web Developer and an early adopter of Node.js whose professional experience has spanned several languages and frameworks, namely Ruby on Rails, C#/VB.NET and the Symfony and Laravel PHP frameworks.


Leave a Reply

Your email address will not be published. Required fields are marked *