How to Set Up a Python Virtual Environment: A Step-by-Step Guide

Python virtual environments keep project dependencies isolated, preventing version conflicts between different projects. This tutorial walks you through creating, activating, and managing a virtual environment using Python’s built-in venv module—no extra tools needed.

Article illustration

Why Use a Virtual Environment?

Each Python project may require specific library versions. A virtual environment creates a self-contained directory with its own Python executable and package installation space. This ensures that changes made to one project don’t affect others or your global Python installation.

Creating a Virtual Environment

Open your terminal and navigate to your project folder. Run the following command (replace myenv with your preferred environment name):

  • python -m venv myenv (on Windows)
  • python3 -m venv myenv (on macOS/Linux)

This creates a folder named myenv containing a fresh Python copy and the pip package manager.

Activating the Environment

Activation points your terminal to the environment’s Python and pip.

  • Windows: myenv\Scripts\activate
  • macOS/Linux: source myenv/bin/activate

Once activated, you’ll see (myenv) at the start of your terminal prompt.

Installing Packages and Working

With the environment active, use pip normally:

  • pip install requests
  • pip install flask

All packages are installed only inside myenv. To freeze your dependencies for sharing, run:

  • pip freeze > requirements.txt

Deactivating the Environment

When you’re done, simply run:

  • deactivate

The terminal prompt reverts to normal, and you’ve left the virtual environment.

Conclusion

Setting up a Python virtual environment is a quick, essential habit that keeps your development clean and conflict‑free. With just a few terminal commands, you isolate project dependencies and make collaboration easier. Start using venv today—you’ll wonder how you ever worked without it.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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