In this tutorial, we'll see how to automatically create requirements.txt in Python.
We'll cover 3 different ways of auto generation of dependencies:
pip freeze > requirements.txt- most generic ones. No need for additional installation.
dephell deps add --from=Pipfil- additional library is needed. It can generate dependencies for a single Python script
pipreqs /path/to/project- additional library is needed. Allow customization in order to extract requirements related to given folder
Example 1: Generate requirements.txt by
requirements.txt for a Python project with virtual environments:
pip freeze > requirements.txt
Before running the command be sure that:
- the virtual environments is activated
- the command will be executed in the same folder as the project
requirements.txt with Python dependencies will be generated in the same folder as the execution.
If you use this command all requirements will be collected from the virtual environment. If you need to get requirements used only in the current project scope then you need to check next options.
Example 2: Auto Generate requirements.txt by
dephell - for a single Python script
Dephell is good option to auto generate
- your project is not using virtual environments
- to generate them only for a single script for a bigger Python project
More information for this package:
dephell is installed by two options:
pip install --user dephell
curl -L dephell.org/install | python3
How to generate requirements for a single Python script? It can be done by a command:
dephell deps convert --from=my_script.py --to=requirements.txt
requirements.txtis the output file
my_script.pyis the file for which dependency list will be build
The structure of the project could be:
../project/src/my_script.py - you need to run the command from folder:
Another option is to use imports like:
dephell deps convert --from=imports --to=requirements.txt
Explanation is available here:
--from – path or format for reading requirements. If it is format then dephell will scan the current directory to find out a file that can be parsed by this converter. If it is filename then dephell will automatically determine file format.
Example 3: Auto Generation of requirements.txt with
Another alternative is
pipreqs. More information is available on this link: github pipreqs.
First the package needs to be installed by:
pip install pipreqs
Generating all dependencies with:
Note Why to use
pip freeze will collect all dependencies from the environments. While
pipreqs will collect requirements used only in the current project!
pip freezeonly saves the packages that are installed with
pip freezesaves all packages in the environment
- if you like to generate
requirements.txtwithout installing the modules