How to creating a virtual environment in Python?

By manoj , 11 March, 2025

Creating a virtual environment in Python is a straightforward process. Virtual environments allow you to manage dependencies for different projects separately, avoiding conflicts between packages. Here's how you can create and use a virtual environment in Python:


Steps to Create a Virtual Environment

1. Using the Built-in venv Module (Python 3.3 and later)

  1. Open a Terminal or Command Prompt:
    • On Windows, use Command Prompt or PowerShell.
    • On macOS/Linux, use the terminal.
  2. Navigate to Your Project Directory:

    cd path/to/your/project
  3. Create the Virtual Environment:
    Run the following command to create a virtual environment:

    python -m venv myenv
    • Replace myenv with the name you want to give your virtual environment.
    • This will create a folder named myenv in your current directory, containing the virtual environment files.
  4. Activate the Virtual Environment:

    • On Windows:

      myenv\Scripts\activate
    • On macOS/Linux:

      source myenv/bin/activate

    Once activated, your terminal prompt will change to show the name of the virtual environment, indicating that it is active.

  5. Install Packages in the Virtual Environment:
    While the virtual environment is active, any packages you install using pip will be isolated to this environment. For example:

    pip install requests
  6. Deactivate the Virtual Environment:
    When you’re done working in the virtual environment, you can deactivate it by running:

    deactivate

2. Using virtualenv (Third-Party Tool)

If you prefer using virtualenv (a popular third-party tool), follow these steps:

  1. Install virtualenv:

    pip install virtualenv
  2. Create a Virtual Environment:

    virtualenv myenv
  3. Activate the Virtual Environment:
    • On Windows:

      myenv\Scripts\activate
    • On macOS/Linux:

      source myenv/bin/activate
  4. Deactivate the Virtual Environment:

    deactivate

Summary of Commands

ActionCommand (Windows)Command (macOS/Linux)
Create virtual environmentpython -m venv myenvpython3 -m venv myenv
Activate environmentmyenv\Scripts\activatesource myenv/bin/activate
Deactivate environmentdeactivatedeactivate

Why Use a Virtual Environment?

  • Isolation: Each project can have its own dependencies without conflicts.
  • Reproducibility: Easily share your project with others by including a requirements.txt file.
  • Cleaner System: Avoid cluttering your global Python installation with unnecessary packages.

Let me know if you need further assistance! 😊

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.