Python

Mastering Python Virtual Environments: A Comprehensive Guide

A virtual environment in Python is an isolated environment that allows you to install and manage packages independently from the global Python installation. This is particularly useful when working on multiple projects that require different dependencies or versions of packages.

 

Why Use a Virtual Environment?

  1. Avoid conflicts: Different projects might need different versions of the same package.
  2. Clean project setup: Keeps your project dependencies self-contained.
  3. Easier deployment: You can list all packages with requirements.txt and replicate the environment elsewhere.

How to Use a Virtual Environment (Step-by-Step)

We will use the venv module, which is built into Python 3.3+.

 Step 1: Create a Virtual Environment

python -m venv venv
  • python: Calls your Python interpreter.
  • -m venv: Tells Python to run the venv module.
  • venv: The name of the directory that will contain the virtual environment.

This will create a folder named venv with all the necessary files to create an isolated environment.

Step 2: Activate the Virtual Environment

On Windows:

venv\Scripts\activate

On macOS/Linux:

source venv/bin/activate

Once activated, your shell prompt will change to something like:

(venv) your-username$

Step 3: Install Packages in the Virtual Environment

Now you can install packages and they will be available only inside this environment.

pip install requests

You can verify with:

pip list

Only packages in the virtual environment will be shown.

Step 4: Freeze the Environment

Create a requirements.txt file listing all installed packages:

pip freeze > requirements.txt

Step 5: Deactivate the Environment

When you're done:

deactivate

This returns you to the global Python environment.

Example Project Structure

my_project/
?
??? venv/                ? Virtual environment files
??? main.py               ? Your Python script
??? requirements.txt      ? List of dependencies

 

Installing Environment from requirements.txt

If you're collaborating or deploying somewhere else:

python -m venv myenv
source myenv/bin/activate
pip install -r requirements.txt

 

 


About author

author image

Amrit panta

Fullstack developer, content creator



Scroll to Top