How to Set Up a Virtual Environment in Python: A Beginner’s Guide
Virtual environments are isolated spaces for Python projects, allowing you to manage dependencies without conflicts between projects. This tutorial walks you through setting up a virtual environment quickly and effectively.
Python includes the built-in venv module, which is the modern standard for creating virtual environments. If you’re using Python 3.3 or later, you’re ready to go—no extra installation required.
Creating a Virtual Environment
Open your terminal or command prompt and navigate to your project directory. Then run:
python -m venv myenv(Windows)python3 -m venv myenv(macOS/Linux)
This creates a folder named myenv containing a complete Python installation and package manager.
Activating the Virtual Environment
Activation changes your shell to use the virtual environment’s Python and tools:
- Windows:
myenv\Scripts\activate - macOS/Linux:
source myenv/bin/activate
Once activated, you’ll see (myenv) in your terminal prompt, confirming the environment is active.
Installing Packages
With the environment active, use pip to install packages without affecting your global Python setup:
pip install requestspip freeze > requirements.txtto export dependencies
Deactivating and Deleting
To exit the virtual environment, run deactivate. To delete it, simply remove the folder—the environment is entirely contained within it.
Using virtual environments keeps your development workflow clean and reproducible. Start using them today for every Python project to avoid dependency headaches.