DevOps | Scripts | Automation

Python

What is requirements.txt in Python?

Need of requirements.txt in Python

People who worked on Python know that the Python language has a vast amount of libraries and packages that you need to install and use as per your script requirements.

However, instructing users or creating a README file for users to download and install all packages before running a script seems a cumbersome task for users as they have to check instructions for which package and which version they have to download to use.

Now just think, how it would be easy for users if a single command installs all the requirements that a script is required?

For example,

Let’s say your script has a requirement to install openpyxl (for Excel), panda, azure-mgmt, and azure-identity modules. How would you have installed Python3 from the terminal?

pip3 install openpyxl
pip3 install panda
pip3 install azure-mgmt
pip3 install azure-identity

In the above example, what if your program grows bigger and bigger? you need to install all libraries one by one and that is time-consuming and sometimes not feasible. This is why we need requirements.txt.

Create a requirements.txt file and mention all the dependencies you need to install. In requirements.txt you can also mention a version of the module.

Below is an example of the requirements.txt file,

openpyxl==3.1.2
panda
azure-mgmt==4.0.0
azure-identity

In the above example, we have mentioned two modules with versions and two without versions. So once we install the requirements.txt file it will install a specific version of that module and others will be installed the latest available on the site.

To install requirements.txt file modules install the below command.

# For python3
pip3 install -r requirements.txt

# For older versions.
pip install -r requirements.txt

Make sure that the requirements.txt is in the same folder that you are running this command. If not then provide the full path of the file.


Best practice with Python Virtual Environment

Just consider the situation where you need to install the above dependencies for your project requirement but the remote server already has the higher or lower version installed that you can’t remove because of the other project requirements.

It is also not feasible to remove and install dependent modules every time on the same machine as per your project requirement.

To tackle this situation, Python’s virtual environment is useful. We have already covered how you can create a virtual environment in Python. Refer to this article: Create Virtual Environment.

Loading