Search code examples
pythonpython-3.xrequirements.txt

Is there a way to automatically add dependencies to requirements.txt as they are installed?


Similar to how Node.js automatically adds dependencies to package-lock.json, is there a way I can automatically add requirements to my requirements.txt file for Python?


Solution

  • Since you mentioned Node.js specifically, the Python project that comes closest to what you're looking for is probably Pipenv.

    Blurb from the Pipenv documentation:

    Pipenv is a dependency manager for Python projects. If you're familiar with Node.js's npm or Ruby’s bundler, it is similar in spirit to those tools. While pip can install Python packages, Pipenv is recommended as it’s a higher-level tool that simplifies dependency management for common use cases.

    It's quite a popular package among developers as the many stars on GitHub attest.

    Alternatively, you can use a "virtual environment" in which you only install the external dependencies that your project needs. You can either use the venv module from the standard library or the Virtualenv package from PyPI, which offers certain additional features (that you may or may not need). With either of those, you can then use Python's (standard) package manager Pip to update the requirements file:

    pip freeze >requirements.txt
    

    This is the "semi-automatic" way, so to speak. Personally, I prefer to do this manually. That's because in a typical development environment ("virtual" or not), you also install packages that are only required for development tasks, such as running tests or building the documentation. They don't need to be installed along with your package on end-user machines, so shouldn't be in requirements.txt. Popular packaging tools such as Flit and Poetry manage these "extra dependencies" separately, as does Pip.