How to Create a Virtual Environment in Python (venv) - Complete Guide

Learn how to create and manage a virtual environment (venv) in Python on Windows, macOS, and Linux. Step-by-step guide with commands and best practices.

How to Create a Virtual Environment in Python (venv) - Complete Guide
Introduction
A virtual environment (venv) in Python allows developers to create an isolated workspace for their projects. This ensures dependencies do not conflict between different projects. In this guide, you’ll learn how to create, activate, and manage a virtual environment in Python on Windows, macOS, and Linux.
Step 1: Install Python (If Not Installed)
Before setting up a virtual environment, ensure you have Python installed. You can check by running:
python --version
If Python is not installed, follow this guide to install it or visit python official site.
Step 2: Create a Virtual Environment
Navigate to your project directory and run the following command:
python -m venv myenv
This will create a virtual environment named myenv
in the current directory.
Step 3: Activate the Virtual Environment
On Windows:
myenv\Scripts\activate
On macOS/Linux:
source myenv/bin/activate
Once activated, your terminal prompt will change to indicate the virtual environment is active.
Step 4: Install Dependencies
After activation, install dependencies using pip
:
pip install package_name
For example, to install Flask:
pip install flask
Step 5: Deactivate the Virtual Environment
To exit the virtual environment, simply run:
deactivate
Step 6: Delete a Virtual Environment
If you no longer need the virtual environment, delete its folder:
rm -rf myenv # macOS/Linux
rd /s /q myenv # Windows
Conclusion
Using a virtual environment in Python is crucial for managing dependencies effectively. It keeps your projects organized and avoids conflicts between different package versions. Start using venv
today and streamline your Python development! 🚀