Last modified: May 25, 2025 By Alexander Williams

Install Python Virtual Environments: venv, virtualenv

Python virtual environments help isolate project dependencies. They prevent conflicts between packages. This guide covers both venv and virtualenv.

Why Use Python Virtual Environments?

Virtual environments keep projects clean. They allow different Python versions and packages per project. This avoids system-wide package conflicts.

Without virtual environments, all projects share the same packages. This can cause version conflicts. Virtual environments solve this problem.

Prerequisites

Before starting, ensure Python is installed. Check our guide on How to Install Python on Windows, macOS, Linux.

You'll also need pip. Learn how to install it in How to Install pip for Python in 3 Easy Steps.

Using Python's Built-in venv

venv comes with Python 3.3+. It's the recommended tool for creating virtual environments.

Create a Virtual Environment

Open your terminal and run:


python -m venv myenv

This creates a folder named myenv with the virtual environment.

Activate the Environment

On Windows:


myenv\Scripts\activate

On macOS/Linux:


source myenv/bin/activate

Your prompt will change to show the active environment.

Deactivate the Environment

To exit the virtual environment:


deactivate

Using virtualenv

virtualenv is an older but powerful alternative. It works with Python 2 and 3.

Install virtualenv

First, install virtualenv using pip:


pip install virtualenv

Create a Virtual Environment

Create a new environment:


virtualenv myenv

This creates a folder with the environment files.

Activate and Use

Activation works the same as with venv. Use the same commands shown earlier.

Managing Packages in Virtual Environments

With the environment active, install packages normally using pip. For example, to install a package for audio processing:


pip install pydub

These packages will only be available in the active environment. Check our guide on How to Install PyDub in Python for more details.

Best Practices

Always use virtual environments for Python projects. Keep each project in its own environment.

Document your dependencies. Use pip freeze > requirements.txt to save them.

For complex projects, consider tools like Poetry or Pipenv. They build on virtual environments.

Conclusion

Python virtual environments are essential for development. They keep your projects organized and conflict-free.

Use venv for Python 3 projects. Use virtualenv if you need Python 2 support.

Remember to activate your environment before working. Deactivate it when done.