Python Virtual Environments with venv

Published on: July 10, 2026
Reading time: 6 minutes
Tela de computador exibindo código

A Python virtual environment creates an isolated place for a project’s interpreter and installed packages. This prevents one project from accidentally changing the dependencies of another and makes development, testing, and deployment more predictable.

Python includes the venv module, so you can create an environment without installing an additional tool. This guide explains why isolation matters, how to create and activate environments on Windows, macOS, and Linux, how to install packages, save dependencies, use VS Code, solve common errors, and remove or rebuild an environment safely.

For related topics, read the guides on Python packages, file paths, and ModuleNotFoundError.

Why Use a Virtual Environment?

Imagine two projects:

  • Project A needs version 2 of a library.
  • Project B needs version 3 of the same library.

If both use the global Python installation, upgrading one dependency may break the other project. A virtual environment gives each project its own package directory.

The official venv documentation describes environment creation and command-line options. The Python Packaging User Guide explains package installation practices.

Check Your Python Installation

Open a terminal and run one of these commands:

python --version

On some systems:

python3 --version

On Windows, the Python launcher may be available:

py --version

Use the command that points to the intended Python version throughout the project.

Create a Project Folder

mkdir weather-project
cd weather-project

Then create the environment:

python -m venv .venv

The name .venv is common because editors recognize it and the leading dot keeps it visually separate from source files. You may choose another name, but use one convention consistently.

Activate venv on Windows

In Command Prompt:

.venv\Scripts\activate.bat

In PowerShell:

.venv\Scripts\Activate.ps1

After activation, the environment name usually appears at the beginning of the terminal prompt.

Activate venv on macOS and Linux

source .venv/bin/activate

Activation modifies the current shell so commands such as python and pip use the environment.

Confirm the Active Interpreter

Check the executable from Python itself:

python -c "import sys; print(sys.executable)"

The path should point inside .venv. You can also inspect pip:

python -m pip --version

Using python -m pip is a reliable habit because it ties pip to the interpreter that executes the command.

Install Packages Inside the Environment

python -m pip install requests

List installed packages:

python -m pip list

Now the package belongs to this project environment instead of the global Python installation. The Requests guide provides a practical package example.

Create a requirements.txt File

Record exact installed versions:

python -m pip freeze > requirements.txt

Another developer can create a new environment and install the same dependencies:

python -m pip install -r requirements.txt

pip freeze records the complete environment. For larger applications, consider a project configuration and dependency tool that distinguishes direct from transitive dependencies.

Deactivate the Environment

deactivate

This returns the shell to its previous Python configuration. Deactivation does not delete any files.

Do Not Commit .venv to Git

A virtual environment contains platform-specific files and can be recreated from dependency declarations. Add it to .gitignore:

.venv/
__pycache__/
*.pyc

Commit your source code and dependency file, not the environment directory.

Use venv in VS Code

Open the project folder, then select the interpreter located inside .venv. In VS Code, use the command palette and choose Python: Select Interpreter. New integrated terminals usually activate the selected environment automatically.

If imports show an error in the editor but work in another terminal, the editor may be using a different interpreter. The VS Code Python guide explains interpreter selection and debugging.

Run a Script Without Activating

Activation is convenient but not required. You can call the environment interpreter directly.

Windows:

.venv\Scripts\python app.py

macOS and Linux:

.venv/bin/python app.py

This approach is useful in scripts, scheduled tasks, and automated workflows because it removes ambiguity.

Choose a Specific Python Version

The environment uses the interpreter that runs -m venv. On Windows:

py -3.12 -m venv .venv

On systems with versioned commands:

python3.12 -m venv .venv

Confirm that the selected version exists before using it.

Upgrade pip Carefully

python -m pip install --upgrade pip

Upgrade tools inside the active environment rather than modifying the operating system’s managed Python installation.

Rebuild a Broken Environment

Virtual environments are disposable. If one becomes inconsistent:

  1. Save the dependency declaration.
  2. Deactivate the environment.
  3. Delete the .venv directory.
  4. Create it again.
  5. Reinstall dependencies.
python -m venv .venv
python -m pip install -r requirements.txt

Do not copy a virtual environment between operating systems or unrelated directory locations. Recreate it instead.

Common Activation Problems

PowerShell Blocks the Script

PowerShell execution policy may prevent Activate.ps1 from running. Use a policy appropriate for your organization, open Command Prompt and use activate.bat, or invoke the environment interpreter directly. Do not weaken system security without understanding the change.

python Is Not Recognized

Python may not be installed or may not be on the PATH. Try the Windows py launcher or verify the installation.

The Package Is Still Missing

Confirm the active interpreter and reinstall with:

python -m pip install package-name

The ModuleNotFoundError guide presents a complete diagnostic workflow.

pip Installs Globally

Use python -m pip --version and check whether its path is inside .venv. If not, activate the environment correctly or call its Python executable directly.

A Complete Beginner Workflow

mkdir api-client
cd api-client
python -m venv .venv
source .venv/bin/activate
python -m pip install requests
python -m pip freeze > requirements.txt
python app.py
deactivate

On Windows, replace the activation command with the appropriate Scripts command.

Use Environment Variables for Secrets

A virtual environment isolates packages, not secrets. Do not store API keys in the .venv directory or commit them in source code. Read credentials from environment variables and validate that required values exist. The environment variables guide explains secure patterns.

venv vs Containers

A virtual environment isolates Python packages. It does not isolate the operating system, system libraries, or network. Containers provide broader process and filesystem isolation. Many projects use both: a virtual environment for local development and a container for deployment.

venv vs Conda

venv is part of Python and works well for standard Python dependencies. Conda can also manage non-Python packages and complete environments, which is useful in some data science workflows. Choose based on the project’s requirements rather than mixing tools without a reason.

Common Mistakes

  • Installing packages before activating the environment.
  • Using pip from a different Python interpreter.
  • Committing .venv to version control.
  • Copying an environment to another computer.
  • Forgetting to document dependencies.
  • Using one environment for many unrelated projects.
  • Deleting the environment without preserving dependency information.
  • Assuming venv protects passwords and tokens.

Frequently Asked Questions

Do I need a virtual environment for every project?

It is a strong default for projects that install packages. Small scripts using only the standard library may not require one, but isolation is still harmless.

Does venv include Python?

It creates an environment based on an existing interpreter and includes links or copies needed to run that environment.

Can I rename .venv?

Moving or renaming an existing environment can break internal paths. Recreate it with the desired name instead.

Should requirements.txt be committed?

Yes, when it is the project’s chosen dependency declaration. It allows collaborators and deployment systems to rebuild the environment.

How do I know venv is active?

Check the terminal prompt and run python -c "import sys; print(sys.executable)".

Conclusion

Python virtual environments keep dependencies isolated and make projects easier to reproduce. Create one inside each project, activate it before installing packages, use python -m pip, document dependencies, and exclude the environment directory from Git.

When an environment becomes unreliable, rebuild it instead of repairing individual files. Treating environments as disposable infrastructure leads to cleaner and more dependable Python projects.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    foto monitor com código
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Free Tools for Beginner Programmers

    Discover free tools for beginner programmers, including code editors, browser environments, practice platforms, Git, databases, documentation, and communities, with a

    Ler mais

    Tempo de leitura: 8 minutos
    10/07/2026
    Comparação entre Google Colab e Jupyter Notebook
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Google Colab vs Jupyter Notebook: Which Is Better?

    Compare Google Colab and Jupyter Notebook for setup, hardware, collaboration, files, privacy, extensions, offline work, reproducibility, and data science projects.

    Ler mais

    Tempo de leitura: 7 minutos
    10/07/2026
    Debug de aplicações Python no Visual Studio Code
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Debug Python in VS Code: Complete Beginner Guide

    Learn to debug Python in VS Code with breakpoints, stepping, variable inspection, watches, conditional breakpoints, and launch configurations.

    Ler mais

    Tempo de leitura: 8 minutos
    10/07/2026
    Transformando scripts Python em executáveis para Windows
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Create Executable Python Scripts Easily

    Learn to create executable Python scripts using PyInstaller: set up a virtual environment, build a single-file .exe, add an icon,

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026
    Transformando script Python em executável EXE rapidamente
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Convert Python Script to .exe in 5 Minutes

    Convert your Python script to .exe in 5 minutes using PyInstaller: virtual environment setup, single-file build, no-console flag, custom icon,

    Ler mais

    Tempo de leitura: 5 minutos
    03/06/2026
    Publicação de pacote Python no PyPI em poucos minutos
    IDEs and Tools
    Foto de perfil de Leandro Hirt da Academify

    Publish Your Python Package to PyPI in 5 Min

    Learn how to publish your Python package to PyPI in 5 minutes: project structure, pyproject.toml, build, API tokens, Twine upload,

    Ler mais

    Tempo de leitura: 6 minutos
    03/06/2026