W3docs

Automatically create requirements.txt

You can use the pip freeze command to automatically generate a requirements.txt file in Python.

You can use the pip freeze command to automatically generate a requirements.txt file in Python. This command lists all of the packages and their versions that are currently installed in your virtual environment. For a quick shell alternative, you can simply run pip freeze > requirements.txt. Here's an example of how to use the command inside a Python script:

Call pip freeze from inside a Python script to automatically generate a requirements.txt file

import subprocess

# Create a requirements.txt file
with open("requirements.txt", "w") as f:
    subprocess.run(["pip", "freeze"], stdout=f)

This script opens a file called requirements.txt in write mode, and then calls the pip freeze command, passing the file object as the stdout argument. This writes the output of the pip freeze command to the file, creating a requirements.txt file containing a list of all the packages and their versions currently installed in your environment. (Note: Ensure your virtual environment is activated before running the script, or specify the full path to pip to avoid using the system-wide interpreter.)

You may also use pipenv instead of pip if you're managing dependencies with Pipenv.

Call pipenv lock -r from inside a Python script to automatically generate a requirements.txt file

import subprocess

# Create a requirements.txt file
with open("requirements.txt", "w") as f:
    subprocess.run(["pipenv", "lock", "-r"], stdout=f)

This will output a flat list of pinned dependencies to the file. (Use pipenv graph if you need to visualize the dependency tree instead.)