PythonModulesBeginner

Virtual Environments (`venv`)

A self-contained directory tree that contains a Python installation for a specific project, isolating its dependencies from other projects.

Review the syntaxStudy the examplesOpen the coding app
python -m venv myenv
source myenv/bin/activate # Unix/macOS
myenv\Scripts\activate # Windows

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

A self-contained directory tree that contains a Python installation for a specific project, isolating its dependencies from other projects.

Virtual environments, primarily managed by the built-in `venv` module (or external tools like `conda` or `pipenv`), are crucial for Python project management. A virtual environment creates an isolated Python installation for a specific project, meaning that any packages installed within it will not affect the global Python installation or other projects. This solves the "dependency hell" problem, where different projects might require different versions of the same library, or where installing a new package for one project could break another. To create one, you typically run `python -m venv myenv` (where `myenv` is the desired directory name). After creation, you "activate" the environment (e.g., `source myenv/bin/activate` on Unix/macOS, `myenv` on Windows), which modifies your shell's `PATH` to use the virtual environment's Python interpreter and its installed packages. Best practices include creating a virtual environment for every new Python project, activating it before installing any project-specific dependencies (using `pip install`), and then generating a `requirements.txt` file (`pip freeze > requirements.txt`) to document and share the project's exact dependencies. This ensures reproducibility and avoids conflicts. The time complexity for creating and activating a `venv` is minimal, primarily involving file system operations. Edge cases include issues with system-wide Python installations or path configurations that might interfere with `venv` activation.

Quick reference

Syntax

python -m venv myenv
source myenv/bin/activate # Unix/macOS
myenv\Scripts\activate # Windows

See it in practice

Examples

1

Creating a virtual environment

# In your project directory:
# Command line:
# python -m venv myproject_env

import os
import sys

env_name = 'myproject_env'
print(f"Creating virtual environment '{env_name}'...")
# os.system(f"python -m venv {env_name}") # For demonstration, usually run directly
print(f"Virtual environment '{env_name}' created.")
print(f"To activate: source {env_name}/bin/activate (Unix/macOS) or {env_name}\Scripts\activate (Windows)")
Output:
Creating virtual environment 'myproject_env'... Virtual environment 'myproject_env' created. To activate: source myproject_env/bin/activate (Unix/macOS) or myproject_env\Scripts\activate (Windows)

The `python -m venv <ame>` command creates a new directory `<ame>` containing a minimal Python installation and a `pip` installer, isolated from the system Python.

2

Activating and installing packages

# Assuming 'myproject_env' exists and is activated:
# (myproject_env) $ pip install requests
# (myproject_env) $ python -c "import requests; print(requests.__version__)"

# Example output if requests is installed:
# 2.31.0

# Example output if requests is NOT installed in the venv:
# Traceback (most recent call last):
#   File "<string>", line 1, in <module>
# ImportError: No module named 'requests'
Output:
2.31.0

After activating the virtual environment, `pip install requests` installs the `requests` library only within that environment. The Python interpreter within the activated environment will find this package.

3

Deactivating and cleaning up

# Assuming 'myproject_env' is activated:
# (myproject_env) $ deactivate

# To remove the virtual environment directory:
# rm -rf myproject_env # Unix/macOS
# rmdir /s /q myproject_env # Windows

# Example output after deactivation:
# $ python -c "import requests" # ImportError: No module named 'requests'
Output:
ImportError: No module named 'requests'

The `deactivate` command (available after activation) reverts the shell's `PATH` to use the system Python. Removing the environment directory completely cleans up all installed packages and the isolated Python installation.

Debug faster

Common Errors

1

Packages installed globally

Cause: Forgetting to activate the virtual environment before running `pip install`. This leads to packages being installed in the system-wide Python, potentially causing conflicts or making project dependencies unclear.

Fix: Always activate your virtual environment (`source myenv/bin/activate` or `myenv\Scripts\activate`) before installing any project-specific packages with `pip`.

# After 'python -m venv myenv' but WITHOUT 'source myenv/bin/activate'
# pip install requests # Installs requests globally, not in myenv
2

ModuleNotFoundError (in activated venv)

Cause: The virtual environment is activated, but a package is still not found. This can happen if the package was installed before activation, or if the wrong Python interpreter was used during installation.

Fix: Ensure the virtual environment is correctly activated. If the package is still missing, try `pip uninstall <package_name>` globally (if it was accidentally installed there) and then `pip install <package_name>` *after* activating the correct virtual environment.

# (myenv) $ python -c "import requests" # ModuleNotFoundError
# (myenv) $ pip install requests # Install it correctly

Runtime support

Compatibility

AnyN/APython 3.3+

Source: Python Docs

Common questions

Frequently Asked Questions

A self-contained directory tree that contains a Python installation for a specific project, isolating its dependencies from other projects.

Packages installed globally: Always activate your virtual environment (`source myenv/bin/activate` or `myenv`) before installing any project-specific packages with `pip`. ModuleNotFoundError (in activated venv): Ensure the virtual environment is correctly activated. If the package is still missing, try `pip uninstall <ame>` globally (if it was accidentally installed there) and then `pip install <ame>` *after* activating the correct virtual environment.