How to Manage Python Application Dependencies?
Application Dependencies Management is the process of managing dependencies of a project which are available in the form of reusuable functions in libraries.
To maintain dependencies of a Python project, you must have the following tools installed on your computer:
- Pip - Pip is a package management utility tool that simplifies installation and management of software packages from Python Package Index (PyPI) and other package indexes. If Pip is not installed on your computer then use this guide to install it first.
- virtualenv - virtualenv is a tool that helps to create an isolated environment for installing dependencies in a Python project. If virtualenv is not installed on your computer then use this guide to install it.
In this tutorial, we will create a Python project, create a virtual environment for the project, and install some dependencies such as MySQL client library for the project.
Follow the steps below to learn how to manage dependencies for a Python project:
- Open a terminal and create a project directory with the name of your choice:
- Navigate to the project directory:
- Create a virtual environment inside your project directory using the following command:
- To install dependencies in the virtual environment of your project, activate your project virtual environment first. Use the following command to activate the virtual environment: On Ubuntu/Linux/Mac
- Now, you can use the pip command from within the environment activated terminal to install dependencies for your project.
Here, env is the name of the virtual environment for this project. The above command creates env folder in the root directory of the project. This env folder contains files and folders such as bin and lib.
On Windows 10, we may get "Running Scripts is Disabled on this System" error. To fix this error, see here.
On successful activation of your project virtual environment, you will see that the next line of the terminal starting with the (env).
Here is an example of pip command that installs MySQL client library in the virtual environment:
pip3 install PyMySQL
Python requirements.txt File
The requirements.txt file in Python is typically used for storing information about all the libraries and packages required to run the project.
How to Generate requirements.txt File?
To generate a requirements.txt file, activate the virtual environment first and then execute the following command:
pip3 freeze > requirements.txt
How to Install Dependencies from a requirements.txt File?
To install dependencies from the requirements.txt file, activate the virtual environment and run the following command:
pip3 install -r requirements.txt