Creating a Python Virtual Environment (venv)
A virtual environment is an independent 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 lets you 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
Virtual environments give each project an independent dependency space, completely eliminating version conflicts
Why do we 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 and do not pollute the global Python
- Controllable dependencies: Through
requirements.txtPrecisely record and reproduce environments - Safe testing: You can safely upgrade or try new packages without affecting other projects
Scenario example:
- Project A requires Django 3.2
- Project B requires Django 4.0
- If installed globally, the two versions conflict
Virtual environment tools
| Tool name | Type | Python version support | Installation method | Feature | Applicable scenarios |
|---|---|---|---|---|---|
| venv(recommended) | Built-in module | ≥ 3.3 | No installation needed, built in | Lightweight, officially recommended, simple to use | General development, everyday projects |
| virtualenv | Third-party tool | 2.x and 3.x | pip install virtualenv |
Feature-rich, compatible with multiple versions | Need compatibility with older versions or advanced features |
| conda | Bundled with Anaconda | 2.x and 3.x | Installed along with Anaconda/Miniconda | Cross-language package management, data science ecosystem | Data science, machine learning projects |
For older version support, you can use virtualenv (Python 2 compatible):
pip install virtualenv # 非必须,venv 通常够用
In this chapter we will use venv to create and manage virtual environments.
Create a virtual environment
Python 3.3+ has the venv module built in, so no extra installation is needed.
Workflow
Workflow overview
1
creation
python -m venv
2
Activate
activate
3
Install dependencies
pip install
4
Develop and debug
python / run
5
Deactivate
deactivate
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 a virtual environment (naming it '.venv' is a common convention)
python3
-m
venv .venv
Parameter Description:
-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/ # 安装的第三方库
Activate the virtual environment
After activation, the python and pip commands in the current terminal automatically point to that virtual environment, and all installation operations take place in the isolated space.
macOS / Linux
source .venv/bin/activate
Windows(CMD / PowerShell)
.venv\Scripts\activate
After a successful activation, the command prompt usually shows the environment name:
(.venv) $
Verify that activation took effect:
# Check Python path, should point to .venv directory
which python # macOS/Linux
where python # Windows
→ /path/to/my_project/.venv/bin/python
Use the virtual environment
Install 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
# Install multiple packages
(.venv) pip install requests pandas
# Slow installation? Use domestic mirror
(.venv) pip install django -i https://pypi.tuna.tsinghua.edu.cn/simple
View installed packages
(.venv) pip list
Package Version
---------- -------
Django 3.2.12
pip 21.2.4
# View details of a package
(.venv) pip show django
# 升级包
(.venv) pip install --upgrade pip
Export dependencies
Using requirements.txt to record and reproduce the project environment is standard practice for team collaboration:
(.venv) pip freeze > requirements.txt
Example contents of a requirements.txt file:
Django==3.2.12
requests==2.26.0
pandas==1.3.3
Install dependencies from a file
(.venv) pip install -r requirements.txt
Tip:Add .venv/ to .gitignore and commit only requirements.txt. Virtual environments are large and path-bound, so they should not be put under version control.
Exit the virtual environment
When you finish your work, you can exit the virtual environment:
deactivate
After exiting, the command prompt returns to normal and the Python and pip commands use the system-wide versions.
Delete a virtual environment
To delete a virtual environment, simply delete the corresponding directory:
# 确保已退出环境
deactivate
Delete a virtual environment
A virtual environment is essentially an ordinary directory; deleting the directory removes it completely:
macOS / Linux
rm -rf .venv
Windows
rmdir /s /q .venv
Note
: Before deleting, please run
deactivate
to exit the environment, otherwise the current shell will keep stale environment variables.
Real 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 a 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. Finish development and exit the environment
(
.venv
)
deactivate
Advanced usage
Specify the Python version
If you have several Python versions installed, you can specify which one to use to create the virtual environment:
python3.8 -m venv .venv # 使用 Python 3.8
Create an environment without pip
python -m venv --without-pip .venv
Create a virtual environment that inherits system packages
python -m venv --system-site-packages .venv
Frequently Asked Questions
1. Why does my virtual environment have no activate script?
Make sure you are using the correct path:
- Windows:
Scripts\activate - Unix/Linux:
bin/activate
2. How can I tell whether I am currently in a virtual environment?
Check whether the command prompt has an environment name prefix, or run:
which python
3. Package installation 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 a virtual environment hard-code absolute paths, so they break after a move. To migrate, the simplest way is to recreate the environment and requirements.txt restore the dependencies.
5. How much space does a virtual environment take?
An empty environment is about 20-50 MB and grows as packages are installed. Data science projects (NumPy, Pandas, PyTorch) can reach several GB. It is a good habit to periodically clean up virtual environments you no longer use.
Best Practices
- One environment per project: Avoid dependencies of different projects affecting each other
- Use a uniform name
.venv: Most IDEs (VS Code, PyCharm) can detect it automatically - Keep it updated
requirements.txt: After everypip install, export again - Ignore the virtual environment in version control: In
.gitignoreAdd to.venv/ - Periodically clean up abandoned environments: Free up disk space
- Pin version numbers in production:
requirements.txtExplicitly write the==version in to avoid accidental upgrades
# .gitignore 推荐配置
.venv/
__pycache__/
*.pyc
.env
*.egg-info/