I have experience with Node.js, where running npm install express --save-dev automatically logs the package in the package.json file along with the version. I’m curious if Python’s pip offers a similar feature. When I install a package in Python, I would like it to be added automatically to my requirements.txt file so that I don’t have to do it manually later.
For instance, if I run:
pip install requests
It would be great to have a flag or option that allows requests==2.28.1 (or whatever version is installed) to be appended to my requirements.txt file immediately. Is there an existing method in pip to do this, or will I need to rely on an external tool?
Currently, I run pip freeze > requirements.txt after each installation, but that replaces the entire file and lists all packages, not just the specific one I wish to add.
Nope, pip doesn’t have anything like npm’s --save-dev flag. I’ve dealt with this for years and found a few workarounds that do the trick. One hack I use is piping pip show output to requirements.txt. After installing a package, I’ll run pip show requests | grep Version | awk '{print "requests==" $2}' >> requirements.txt. Not pretty, but it works. pip-tools is another option - gives you a cleaner setup with pip-compile. You keep a requirements.in file with just your main packages, then generate a locked requirements.txt. This splits your direct dependencies from the transitive ones, which sounds like what you want. You could also switch to pipenv or poetry since they handle dependencies more like npm, but that means overhauling your entire workflow.
While pip doesn’t offer an automatic way to save installed packages to a requirements file, you can create a custom shell function to streamline the process. I typically set up a function that combines installation and updating the requirements file in one command. For example, using pip install $1 && echo "$1==pip show $1 | grep Version | cut -d’ ’ -f2" >> requirements.txt will help. Alternatively, consider using a dependency manager like Poetry, which simplifies managing package versions and dependencies significantly.