How to Use Python venv: Create and Manage Virtual Environments

Prakash Bhandari (PB)

Prakash Bhandari (PB)Loading..

Published , Last updated

 Like 
Bookmark    

When working on multiple Python projects where each one needs different versions of the same package, things can quickly get messy. That’s where Python’s venv comes to the rescue. It lets you create clean, isolated environments for each project so your dependencies don’t clash. Whether you're just starting out or already building bigger apps, understanding how to use venv is an essential skill that will save you a lot of headaches.

What Is venv in Python?

Python’s venv module allows you to create isolated environments where you can install packages without affecting your global Python setup.

Why Use a Virtual Environment?

  • Avoid dependency conflicts across projects.
  • Keep your global Python installation clean.
  • Easily replicate environments on different machines.

 

1. How to Create a Virtual Environment

Prerequisites:

  • Python 3.x or newer installed.

 

2. Creating a venv

Run in your command-line shell (terminal or PowerShell) inside your project folder:

# Recommended naming: venv or .venv
python3 -m venv venv

This sets up a new environment shell in the venv/ directory .

 

3. Activating your virtual environment

macOS / Linux:

source venv/bin/activate

Windows PowerShell:

.\venv\Scripts\Activate.ps1

Windows CMD:

venv\Scripts\activate.bat

After activation, your prompt will show (venv) indicating you're now working inside that environment

 

4. Installing packages

Once activated, run:

python -m pip install <package-name>

This installs the package only inside the virtual environment using its local pip ⎯ not globally

 

5. Deactivating

When you're done:

deactivate

This returns your prompt and python command to your system-wide Python

 

6. Removing the venv

If you're finished with the environment:

1. Ensure it's deactivated:

deactivate

2. Then delete the folder:

  1. macOS/Linux:
    1. rm -rf venv
  2. Windows:
    1. rmdir /s venv

 

Behind the scenes (briefly)

  • venv creates a folder containing a Python interpreter, pyvenv.cfg, and a site-packages directory.
  • Activation tweaks your PATH so that python/pip point to that local interpreter

 

Additional tips

  • Use .venv naming to hide the directory in Unix-like systems.
  • Add venv/ or .venv/ to your .gitignore to avoid committing it.

You can create environments that mirror different Python versions by specifying a particular interpreter:

python3.13 -m venv venv-3.11

 

Python’s venv is a powerful but simple way to keep your projects organized, safe, and dependency-conflict-free. It’s a must-know tool for every Python developer from beginner to pro.

 

Discussion (0)

Login to Post Comment!