Creating Python Virtual Environments (venv)

A virtual environment is an isolated Python runtime space with its own interpreter, installed packages, and configuration, completely isolated from the system-wide environment.

A Python virtual environment is an independent Python runtime environment that allows you to create isolated Python environments for different projects on the same machine.

Different projects can run in parallel in their own virtual environments without interfering with each other.

Each virtual environment has its own:

  • Python interpreter
  • Installed packages/libraries
  • Environment variables
Global installation (version conflicts) ✓ Virtual environment (completely isolated) Global Python environment site-packages (shared by all projects) Project A Needs Django 3.2 Project B Needs Django 4.0 Version conflict, cannot coexist Project A .venv Installs Django 3.2 independently Project B .venv Installs Django 4.0 independently

Virtual environments give each project its own dependency space, completely eliminating version conflicts.

Why You Need Virtual Environments

  • Project isolation: different projects can use different versions of Python and third-party libraries
  • Avoid pollution: installed packages only affect the current environment, not the global Python
  • Dependency control: throughrequirements.txtprecisely record and reproduce environments
  • Safe testing: you can safely upgrade or try new packages without affecting other projects

Example scenario:

  • Project A needs Django 3.2 version
  • Project B needs Django 4.0 version
  • If installed globally on the system, the two versions will conflict

Virtual Environment Tools

Tool name Type Python version support Installation method Features Applicable scenarios
venv(Recommended) Built-in module ≥ 3.3 No installation required, built-in Lightweight, officially recommended, easy to use General development, daily projects
virtualenv Third-party tool 2.x and 3.x pip install virtualenv Feature-rich, supports multiple versions For compatibility with older versions or advanced features
conda Comes with Anaconda 2.x and 3.x Installed with Anaconda/Miniconda Cross-language package management, data science ecosystem Data science, machine learning projects

For support of older versions, you can use virtualenv (Python 2 compatible):

pip install virtualenv  # 非必须,venv 通常够用

In this chapter, we will usevenvto create and manage virtual environments.


Creating a Virtual Environment

Python 3.3+ includes the built-invenvmodule, no additional installation required.

Usage Workflow

Workflow Overview

1
Create
python -m venv
2
Activate
activate
3
Install dependencies
pip install
4
Develop and debug
python / run
5
Deactivate
deactivate
Box 1: Create (purple) Create environment python -m venv Box 2: Activate (teal) Activate source activate Box 3: Install (teal) Install dependencies pip install Box 4: Develop (teal) Develop and run python / test Box 5: Deactivate (gray) Deactivate deactivate While activated: the pip and python commands point to the virtual environment, without affecting the global environment.

Check the Python version:

python3 --version
# 或者
python --version

Create a virtual environment:

# 基本语法
python3 -m venv 环境名称

For example, create a virtual environment named.venv:

Example

# Enter the project directory
mkdir my_project && cd my_project

# Create the virtual environment (naming it '.venv' is a common convention)
python3 -m venv .venv

Parameter descriptions:

  • -m venv: use the venv module
  • .venv: the name of the virtual environment (can be customized)

Directory Structure After Creation

.venv/
├── bin/            # 在 Unix/Linux 系统上
│   ├── activate    # 激活脚本
│   ├── python      # 环境 Python 解释器
│   └── pip         # 环境的 pip
├── Scripts/        # 在 Windows 系统上
│   ├── activate    # 激活脚本
│   ├── python.exe  # 环境 Python 解释器
│   └── pip.exe     # 环境的 pip
└── Lib/            # 安装的第三方库

Activating the Virtual Environment

After activation, the python and pip commands in the current terminal will automatically point to the virtual environment, and all installation operations are performed in the isolated space.

macOS / Linux

source .venv/bin/activate

Windows(CMD / PowerShell)

.venv\Scripts\activate

After successful activation, the command-line prompt usually displays the environment name:

(.venv) $

Verify that activation is effective:

# 查看 Python 路径,应指向 .venv 目录
which python       # macOS/Linux
where python       # Windows
→ /path/to/my_project/.venv/bin/python

Using the Virtual Environment

Installing Packages

In an activated environment, packages installed with pip only affect the current environment:

pip install package_name

For example:

# 安装单个包(如Django)
(.venv) pip install django==3.2.12

# 安装多个包
(.venv) pip install requests pandas

# 安装速度慢?使用国内镜像
(.venv)  pip install django -i https://pypi.tuna.tsinghua.edu.cn/simple

Viewing Installed Packages

(.venv) pip list
Package    Version
---------- -------
Django     3.2.12
pip        21.2.4

# 查看某个包的详情
(.venv) pip show django

# 升级包
(.venv) pip install --upgrade pip

Exporting Dependencies

Using requirements.txt to record and reproduce the project environment is a standard practice for team collaboration:

(.venv) pip freeze > requirements.txt

Example contents of the requirements.txt file:

Django==3.2.12
requests==2.26.0
pandas==1.3.3

Installing Dependencies from a File

(.venv) pip install -r requirements.txt

Tip:Add .venv/ to .gitignore and only commit requirements.txt. Virtual environments are large in size and path-bound, so they should not be included in version control.


Deactivating the Virtual Environment

When you're done working, you can deactivate the virtual environment:

deactivate

After deactivation, the command-line prompt returns to normal, and Python and pip commands will use the system-wide versions.


Deleting the Virtual Environment

To delete a virtual environment, simply delete its corresponding directory:

# 确保已退出环境
deactivate

Deleting the Virtual Environment

A virtual environment is essentially an ordinary directory; deleting the directory completely removes it:

macOS / Linux

rm -rf .venv

Windows

rmdir /s /q .venv
Note: Before deleting, rundeactivateto deactivate the environment; otherwise, the current shell will keep invalid environment variables.

Real-World Project Example

Suppose you are developing a Django project:

Example

# 1. Create and enter the project directory
mkdir my_site && cd my_site

# 2. Create and activate the virtual environment
python3 -m venv .venv
source .venv/bin/activate    # Windows: .venv\Scripts\activate

# 3. Install Django and record dependencies
(.venv) pip install django==4.2
(.venv) pip freeze > requirements.txt

# 4. Initialize the Django project
(.venv) django-admin startproject config .

# 5. Run database migrations and start the development server
(.venv) python manage.py migrate
(.venv) python manage.py runserver

# 6. Development finished, deactivate the environment
(.venv) deactivate

Advanced Usage

Specifying a Python Version

If you have multiple Python versions installed, you can specify which version to use to create the virtual environment:

python3.8 -m venv .venv  # 使用 Python 3.8

Creating an Environment Without pip

python -m venv --without-pip .venv

Creating a Virtual Environment That Inherits System Packages

python -m venv --system-site-packages .venv

Frequently Asked Questions

1. Why doesn't my virtual environment have an activate script?

Make sure you are using the correct path:

  • Windows: Scripts\activate
  • Unix/Linux: bin/activate

2. How do I know if I'm currently in a virtual environment?

Check whether the command-line prompt has an environment name prefix, or run:

which python

3. Installing packages is slow

Use a domestic mirror source:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple package_name

Check whether the Python interpreter path is inside the virtual environment directory.

4. Can a virtual environment be moved?

Not recommended. The scripts and configuration files inside the virtual environment have hardcoded absolute paths, so they become invalid after moving. If migration is needed, the simplest way is to recreate the environment and userequirements.txtto restore dependencies.

5. How much space does a virtual environment take up?

An empty environment is about 20–50 MB, and grows as more packages are installed. Data science projects (NumPy, Pandas, PyTorch) can reach several GB. It is a good habit to periodically clean up virtual environments that are no longer used.


Best Practices

  1. Use a separate environment for each project: to avoid dependencies from different projects interfering with each other
  2. Use a unified naming convention:.venv: most IDEs (VS Code, PyCharm) can automatically recognize it
  3. Update promptlyrequirements.txt: every timepip installthen export in sync
  4. Ignore virtual environments in version control: in.gitignoreadd.venv/
  5. Periodically clean up abandoned environments: to free up disk space
  6. Pin version numbers in production:requirements.txtexplicitly write in==versions, avoiding accidental upgrades
# .gitignore 推荐配置
.venv/
__pycache__/
*.pyc
.env
*.egg-info/
Other Extensions