How to create and activate the virtual environment(.venv) in Code Editor(VS Code/Cursor)
How to create and activate the virtual environment(.venv) in Code Editor(VS Code/Cursor)

How to create and activate the virtual environment(.venv) in Code Editor(VS Code/Cursor)

For any Python developer, managing project dependencies is paramount. This is where Python virtual environments (.venv) shine, isolating your project’s dependencies from global Python installations. Visual Studio Code (VS Code) offers seamless integration with these environments, making your development workflow robust and predictable.

This post will guide you through creating, activating, and deactivating a .venv right within your VS Code/Cursor setup.

Why Use a .venv?

A virtual environment ensures that each of your Python projects has its own dedicated set of libraries and dependencies. This prevents conflicts between different projects requiring different versions of the same package, keeping your workspace clean and your projects stable.

Step 1: Creating Your own .venv

You can create a virtual environment directly from VS Code’s integrated terminal.

  1. Open your project folder in VS Code.
  2. Open the integrated terminal (Terminal > New Terminal, or Ctrl + Shift + ).

Step 2: Activating/Enter Your .venv

Activating the virtual environment modifies your shell’s PATH variable to ensure that any Python commands (like python or pip) execute within the context of your virtual environment, not your global Python installation.

The activation command varies based on your terminal shell:

  • For Command Prompt (CMD) on Windows:
    .venv\Scripts\activate.bat
  • For Bash / Git Bash / WSL (Windows Subsystem for Linux) / macOS / Linux:
    source .venv/bin/activate

Once activated, you’ll typically see the name of your virtual environment (e.g., (.venv)) prefixed to your terminal prompt, indicating that it’s active, as the following picture is showing (Powershell example):

Usually install all the dependencies with “pip” tool after going into .venv.

Step 3: Deactivating/Quit Your .venv

Your terminal prompt will return to its normal state, indicating that you’ve exited the virtual environment.

Conclusion

Embracing virtual environments is a crucial step towards robust and manageable Python development. With VS Code’s excellent integration, creating, activating, and deactivating these environments becomes a seamless part of your daily coding routine, empowering you to build more reliable and scalable applications. Leverage this practice to take your Python projects to the next level!

Leave a Reply

Your email address will not be published. Required fields are marked *