Python Virtual Environments

Prashant Kumbhare
2 min readSep 7, 2023

--

Problem Statement: I am working on multiple python projects on my machine at a time. Every project requires its own set of packages, sometimes with a specific version.

1. How do I keep track of all packages required for the project and list them in requirements.txt file so that it can be used at the time of deployment on another host.

2. How do I avoid conflicts between projects, say project A require a different version of a package than project B.

Solution: Python Virtual Environments, Each python project should have its own Virtual Environment with its own dependent packages

Image soure: https://www.dataquest.io/wp-content/uploads/2022/01/python-virtual-envs1.webp

How to use Python Virtual Environment

Install Virtualenv

pip install virtualenv

Create Virtual Environment

virtualenv env_name

A new directory will be created, which contains necessary python executables.

You can also specify interpreter of your choice.

virtualenv -p c:\program files\python38 env_name

Activate Virtual Environment

env_name\Scripts\activate.bat

As you can see Vitual Environment will have only basic packages at the beginning. But now you can start installing packages as required.

Install packages and prepare Requirements file

Use Pip to intall packages as usually done

prepare requirements.txt

pip freeze > requirements.txt

Now this file can be used while deploying application on any other host.

Deactivate Environment

deactivate

Remove Virtual Environment

Simply delete the virtual environment directory.

rmdir env_name /s

--

--

Prashant Kumbhare
Prashant Kumbhare

Written by Prashant Kumbhare

Learning Enthusiast, Runner, Yoga Practitioner, Devops Engineer by profession working for a Banking Firm

No responses yet