. Advertisement .
. Advertisement .
The tutorial introduces how to create requirements.txt file in Python using three methods.
What Is Requirements.txt File In Python?
Python requirements.txt file is built to store information about all modules, libraries, and packages. These features are used to develop a particular project.
This file often resides in your project’s root directory. This way, it can solve all compatibility issues. If your project is too big, it will keep track of all packages to avoid unexpected surprises.
How To Create Requirements.txt File In Python
There are various methods to create a requirements.txt file.
Method 1: Use Virtualenv
Virtualenv is a library letting you create a virtual environment. Run the code pip install virtualenv to install and work with this function. Inside the project directory, you need to create a new virtual environment with the python3 -m venv name_of_env code.
Now, use the pip3 freeze (in Python 3) or the pip freeze (in Python 2) command: pip3 freeze > requirements.txt
Method 2: Use Pipenv
Pipenv comes with such wonderful features that it becomes a perfect virtual environment creation library. Run the following command to install:
# Install pip install pipenv # Install Your Packages for the project pipenv install mypackage # Activate Virtual Env pipenv shell # Run a script in the virtual env pipenv run python myscript.py
As this function automatically keeps track of all libraries in a Pipfile.lock file, it can work as a requirments.txt file. Thus, you can use it as a substitute.
Yet, if you want to create a requirements.txt file, run the following command:
pipenv -r lock >> requirements.txt
Method 3: Use Pipreqs
Pipreqs doesn’t require a virtual environment. It scans the Python script and file automatically for your imported libraries. Then, it creates a requirements.txt file.
Use the pip install pipreqs command to install it.
Here is how to get the requirements.txt file:
How To Maintain A Python Requirements.txt File
Step 1: Use the pip list –outdated to output all outdated packages.
Package Version Latest Type ——————– ——- —— —– click 7.1.2 8.0.3 wheel fastapi 0.63.0 0.70.0 wheel gast 0.3.3 0.5.3 wheel h5py 2.10.0 3.6.0 wheel numpy 1.18.5 1.21.4 wheel pip 20.0.2 21.3.1 wheel setuptools 44.0.0 59.5.0 wheel starlette 0.13.6 0.17.1 wheel tensorflow 2.3.1 2.7.0 wheel tensorflow-estimator 2.3.0 2.7.0 wheel uvicorn 0.12.2 0.15.0 wheel
Step 2: Use the pip install -U PackageName to upgrade the needed packages. In the above example, we will update fastapi:
pip install -U fastapi
Successfully installed anyio-3.4.0 fastapi-0.70.0 sniffio-1.2.0 starlette-0.16.0
Step 3: Check all the tests
Step 4: Run the pip freeze > requirements.txt command to update all requirements files.
Step 5: Run git push and git commit in the production branch.
There are three methods to create requirements.txt file in Python. You can use virtualenv, Pipenv, and pipreqs depending on your needs.