Python Venv
## Python3.x Creating Python Virtual Environment (venv)
A virtual environment is an isolated Python runtime space with its own interpreter, installed packages, and configuration, completely separated from the system's global environment.
Python Virtual Environment is an isolated 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 respective 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 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
* **Controllable Dependencies**: Use `requirements.txt` to precisely record and reproduce environments
* **Safe Testing**: You can safely upgrade or try new packages without affecting other projects
**Example Scenarios:**
* Project A requires Django 3.2
* Project B requires Django 4.0
* If installed globally in the system, the two versions would conflict
### Virtual Environment Tools
| Tool Name | Type | Python Version Support | Installation | Features | Use Cases |
| --- | --- | --- | --- | --- | --- |
| **venv** (Recommended) | Built-in Module | β₯ 3.3 | No installation needed, built-in | Lightweight, officially recommended, easy 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 to support 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 older version support, you can use virtualenv (Python 2 compatible):
pip install virtualenv # Not required, venv is usually sufficient
In this chapter, we will use venv to create and manage virtual environments.
* * *
## Creating a Virtual Environment
Python 3.3+ has the built-in `venv` module, no additional installation needed.
### Usage Process
## Usage Process Overview
1
Create
python -m venv
2
Activate
activate
3
Install Dependencies
pip install
4
Develop/Debug
python / run
5
Deactivate
deactivate
Check Python version:
python3 --version # or python --version
Create a virtual environment:
# Basic syntax python3 -m venv environment_name
For example, create a virtual environment named `.venv`:
## Example
# Enter the project directory
mkdir my_project &&cd my_project
# Create virtual environment (naming it '.venv' is a common convention)
python3 -m venv .venv
**Parameter Description:**
* `-m venv`: Use the venv module
* `.venv`: Name of the virtual environment (can be customized)
### Directory Structure After Creation
.venv/βββ bin/ # On Unix/Linux systemsβ βββ activate # Activation scriptβ βββ python # Environment Python interpreterβ βββ pip # Environment's pipβββ Scripts/ # On Windows systemsβ βββ activate # Activation scriptβ βββ python.exe # Environment Python interpreterβ βββ pip.exe # Environment's pipβββ Lib/ # Third-party libraries installed
* * *
## Activating the Virtual Environment
After activation, the python and pip commands in the current terminal will automatically point to this virtual environment, and all installation operations will be performed in the isolated space.
#### macOS / Linux
source .venv/bin/activate
#### Windows (CMD / PowerShell)
.venvScriptsactivate
After successful activation, the command line prompt usually displays the environment name:
(.venv) $
Verify activation:
# Check Python path, should point to .venv directory which python # macOS/Linuxwhere python # Windowsβ /path/to/my_project/.venv/bin/python
* * *
## Using the Virtual Environment
### Installing Packages
In an activated environment, packages installed with pip will only affect the current environment:
pip install package_name
For example:
# Install a single package (like 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 specific package(.venv) pip show django # Upgrade packages(.venv) pip install --upgrade pip
### Export Dependencies
Using requirements.txt to record and reproduce the project environment is the standard practice for team collaboration:
(.venv) pip freeze > requirements.txt
Example requirements.txt content:
Django==3.2.12 requests==2.26.0 pandas==1.3.3
### Install Dependencies from File
(.venv) pip install -r requirements.txt
> **Tip:** Add .venv/ to .gitignore, only commit requirements.txt. Virtual environments are large and path-bound, and should not be included in version control.
* * *
## Exiting the Virtual Environment
When you're done working, you can exit the virtual environment:
deactivate
After exiting, the command line prompt will return to normal, and Python and pip commands will use the system's global version.
* * *
## Deleting the Virtual Environment
To delete a virtual environment, simply delete the corresponding directory:
# Make sure you've exited the environment deactivate
### Deleting the Virtual Environment
A virtual environment is essentially a regular directory; deleting the directory completely removes it:
#### macOS / Linux
rm -rf .venv
#### Windows
rmdir /s /q .venv
**Note:** Please execute `deactivate` to exit the environment before deleting, otherwise the current Shell will retain invalid environment variables.
* * *
## Real Project Example
Assume you're developing a Django project:
## Example
# 1. Create and enter project directory
mkdir my_site &&cd my_site
# 2. Create virtual environment and activate
python3 -m venv .venv
source .venv/bin/activate # Windows: .venvScriptsactivate
# 3. Install Django and record dependencies
(.venv) pip install django==4.2
(.venv) pip freeze > requirements.txt
# 4. Initialize Django project
(.venv) django-admin startproject config .
# 5. Migrate database and start development server
(.venv) python manage.py migrate
(.venv) python manage.py runserver
# 6. Development complete, exit environment
(.venv) deactivate
* * *
## Advanced Usage
### Specify Python Version
If you have
YouTip