Skip to content

虚拟环境

Isolate 项目 dependencies 使用 venv, activate and deactivate, and manage 多个 Python versions.

你将学到

  • 创建虚拟环境使用 venv
  • Activate and deactivate 环境
  • 理解为什么 isolation matters
  • Use 需求.txt 到 pin dependencies
  • Manage 多个 Python versions

概念讲解

Why Virtual Environments?

Without virtual environments, all your Python projects share the same global site-包 directory. If Project A needs Django 3 and Project B needs Django 4, they conflict. Virtual environments solve this by giving each project its own isolated Python environment with its own package directory.

A virtual environment is a self-contained directory containing:

  • A Python interpreter (symlink to a specific version)
  • Its own site-包 directory
  • Its own installed packages
  • Activation scripts

Creating a Virtual Environment

Use the built-in venv module (Python 3.3+):

# Create a virtual environment named 'venv' (or '.venv')
python -m venv venv

# Or specify a Python version
python3.11 -m venv venv

This creates a venv/ directory containing the isolated Python environment. The common convention is to name it .venv (with a dot) so it is hidden in file explorers, or venv (without a dot).

Activating

Activation modifies your shell's PATH so the virtual environment's Python and pip are used first:

# Windows (Command Prompt)
venv\Scripts\activate

# Windows (PowerShell)
venv\Scripts\Activate.ps1

# macOS / Linux
source venv/bin/activate

After activation, your prompt changes to show the environment name:

(venv) $ python --version
(venv) $ pip install django

Now python and pip refer to the virtual environment's versions, and installed packages go into venv/lib/site-包/ instead of the global directory.

Deactivating

deactivate

This restores your shell to the global Python environment. The virtual environment still exists on disk — you can reactivate it anytime with the activate command.

requirements.txt

Pin your dependencies in a 需求.txt file so others can reproduce your environment:

# requirements.txt
django==4.2.7
requests>=2.31.0
numpy~=1.26.0
pytest==7.4.3

Install from it:

pip install -r requirements.txt

Generate it from your current environment:

pip freeze > requirements.txt

Pin exact versions (==) for reproducible builds. Use >= only if you intentionally want to allow upgrades. The ~= operator allows patch upgrades (e.g., ~=1.26.0 allows 1.26.x but not 1.27).

.gitignore

Never commit the virtual environment directory — it is platform-specific and large. Add it to .gitignore:

# .gitignore
venv/
.venv/
env/
__pycache__/

Commit 需求.txt instead — anyone can recreate the environment from it.

Multiple Python Versions

To manage multiple Python versions on one machine:

  • pyenv (macOS/Linux) — install and switch between Python versions
  • pyenv-win (Windows) — Windows port of pyenv
  • Official Python installer — install multiple versions side by side
# With pyenv
pyenv install 3.11.7
pyenv install 3.12.1
pyenv local 3.11.7   # set version for current directory

# Create a venv with a specific version
python3.11 -m venv venv311
python3.12 -m venv venv312

Modern Alternatives

  • poetry — dependency management and packaging in one tool
  • pipenv — Pipfile + Pipfile.lock for deterministic environments
  • uv — ultra-fast Rust-based replacement for pip and venv
  • conda — popular in data science, manages non-Python dependencies too

For beginners, venv + pip + 需求.txt is the standard starting point. Graduate to poetry or uv as your projects grow.

示例代码

              # --- Creating and using a virtual environment ---
# These are shell commands, not Python code:

# 1. Create the virtual environment
#    python -m venv .venv

# 2. Activate it
#    Windows:  .venv\Scripts\activate
#    macOS:    source .venv/bin/activate

# 3. Install packages (they go into .venv, not global)
#    pip install django requests

# 4. Save dependencies
#    pip freeze > requirements.txt

# 5. Deactivate when done
#    deactivate

# --- requirements.txt example ---
# django==4.2.7
# requests>=2.31.0,<3.0.0
# numpy~=1.26.0
# pytest==7.4.3

# --- .gitignore example ---
# .venv/
# venv/
# __pycache__/
# *.pyc

# --- Python code to check which environment you're in ---
import sys
import os

# Check if running in a virtual environment
in_venv = hasattr(sys, 'real_prefix') or (
    hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
)
print(f"Running in virtual environment: {in_venv}")
print(f"Python executable: {sys.executable}")
print(f"Prefix: {sys.prefix}")

# List installed packages
import subprocess
result = subprocess.run(
    [sys.executable, "-m", "pip", "list"],
    capture_output=True, text=True
)
print("Installed packages:")
print(result.stdout[:500])  # first 500 chars
            

Shows 完整 venv workflow: 创建, activate, 安装, freeze, deactivate. 包含需求.txt 示例, .gitignore 条目, and Python code 到 detect and inspect current 虚拟环境.

动手试一试

常见错误

错误写法

Committing 虚拟环境 directory 到 version control

正确做法

venv directory 是 platform-特定, 大, and 不 portable. 添加 'venv/' and '.venv/' 到 .gitignore and 提交需求.txt 相反. Anyone 能 recreate 环境使用 'pip 安装 -r 需求.txt'.

错误写法

Forgetting 到 activate 虚拟环境之前安装包

正确做法

如果你 运行 pip 安装不使用 activating, 包 go 到全局 Python 环境, affecting 所有项目. 总是 activate 首先: 检查那个你的 prompt shows (venv) 之前安装. Use '哪个 python' 到验证你 是 using venv's Python.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误