How do I Create and Activate a Virtual Environment?

Learn how to create and activate a virtual environment in Python using VS Code. Isolate dependencies and keep your projects organized with this essential setup guide.

Introduction

When working on Python projects, it is essential to use a virtual environment. A virtual environment allows you to isolate project dependencies, preventing conflicts between different projects. This guide explains how to create and activate a virtual environment in Python using VS Code.


Step 1: Open Your Project Folder in VS Code

  • Launch VS Code.
  • Open your project folder by clicking FileOpen Folder (Windows/Linux) or Open… (macOS).
  • Alternatively, use the command line to navigate to your project folder and open VS Code:
    cd path/to/your/project
    code .

Step 2: Create a Virtual Environment

To create a virtual environment, use the following command inside your project folder:

  • Windows: python -m venv venv
  • macOS/Linux: python3 -m venv venv

This creates a folder named venv inside your project directory, which contains the isolated environment.


Step 3: Activate the Virtual Environment

  • Windows (Command Prompt): venv\Scripts\activate
  • Windows (PowerShell): venv\Scripts\Activate.ps1
  • macOS/Linux: source venv/bin/activate

Once activated, you should see the virtual environment name in your terminal prompt, indicating that it is active.


Step 4: Verify That the Virtual Environment Is Active

  • Run the following command to check the Python interpreter being used: python --version
  • If the correct Python version is displayed, your virtual environment is set up correctly.

Step 5: Deactivate the Virtual Environment

  • To exit the virtual environment, simply run: deactivate
  • This returns you to the system-wide Python installation.

Final Thoughts

Using a virtual environment in Python is a best practice for managing project dependencies. It helps avoid conflicts and ensures that each project has its own isolated dependencies.

Next Step: Learn how to install Python packages with pip in our next guide: How Do I Install Python Packages with pip?

Share the Post:

Related Posts