Python : Virtual Environment + requirments.txt

prabhuvikas

Vikas Prabhu

Posted on June 20, 2023

Python : Virtual Environment + requirments.txt

Python projects must always be developed in isolated environments or virtual environment so that all our dependencies are locked to that single project only.

requirements.txt in Python is package.json of NodeJS

It contains all the packages required for running the python project.

Lets see how we can create a virtual environment in Python and generate a requirements.txt file

Creating & Managing Virtual Environment

Install

virtualenv is a tool to create isolated environment in Python. Install this tool using apt-get

fire the following command on bash terminal

$ sudo apt-get install python3-venv
Enter fullscreen mode Exit fullscreen mode

Initialize

traverse to the project folder and run the following command

$ virtualenv venv
Enter fullscreen mode Exit fullscreen mode

this creates a copy of Python in whichever directory you ran the command in, placing it in a folder named venv

Activate

to begin using the virtual environment, it needs to be activated using the following command

$ source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

install any new modules without affecting system default Python or other virtual environments using pip/pip3

$ pip3 install numpy scipy matplotlib
Enter fullscreen mode Exit fullscreen mode

these packages will be installed in the project folder only under venv folder

now we can generate requirements.txt using following command

$ pip3 freeze --local > requirements.txt
Enter fullscreen mode Exit fullscreen mode

--local argument ensures only virtual environment packages are written to requirements.txt

Deactivate

once your work is completed you stop the virtual environment

$ deactivate
Enter fullscreen mode Exit fullscreen mode

Delete

There might be a case where you want to remove the virtual environment. You can simple do this my deleting the venv folder.

💖 💪 🙅 🚩
prabhuvikas
Vikas Prabhu

Posted on June 20, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related