Python virtual environment venv complete guide

Why do we need a virtual environment?

Assume this scenario: You are working on two Python projects at the same time. One is to usepandas 1.5.xAn old project for data analysis, the other one is usingpandas 2.2.xBuilding new services for REST APIs. If you plug both versions of pandas into the global Python environment of your computer, there will be only one outcome - dependency conflicts and project crash.

This is where Virtual Environments come in. venvIt is an official built-in virtual environment tool since Python 3.3. Its core value is very clear:

  1. Thorough isolation management – Each project has an independent set of Python packages, and can even be bound to a specific Python interpreter version.
  2. Zero-pollution global environment – No longer need to fill the system Python with various scattered third-party libraries.
  3. Simplified dependency sharing – One-click export, one-click installation, team collaboration or cross-device deployment are easy.
  4. 100% reproducible operating conditions – No matter which computer you are on, as long as you get the dependency list, you can restore a completely consistent development environment.

Starting from scratch: creation and activation

Pre-check

Please make sure you have Python 3.3 or higher installed on your computer. Open the terminal and enter the following command to see the version number:

python --version

Windows users can also use:

py -3 --version

Step 1: Create a "home" for the project

Create a new project directory anywhere and store all code and configuration files in it:

mkdir my_blog_project
cd my_blog_project

Step 2: UsevenvOne-click generation

The recommended creation command is very short, with the finalvenvis the directory name of the virtual environment (you can also change it to.venvHidden directory like this):

python -m venv venv

💡 Tips Under Linux/macOS, hide directory names (e.g..venv) can make the folder list tidier and is recommended for projects. PowerShell for Windows is also perfectly recognized.

After execution, the directory structure is roughly as follows (there are slight differences in different systems):

my_blog_project/
├── venv/               # 虚拟环境核心
│   ├── bin/            # macOS/Linux:存放 python、pip 和激活脚本
│   ├── Scripts/        # Windows:存放可执行文件
│   ├── lib/
│   │   └── python3.x/
│   │       └── site-packages/  # 👈 虚拟环境装包的位置
│   ├── include/
│   └── pyvenv.cfg      # 虚拟环境配置文件
└── (你的项目代码)

Step 3: Activate the virtual environment (must do it!)

After activation, the terminal will be "locked" in this virtual environment, and allpythonandpipOperations will only affectsite-packagescontent inside.

Linux / macOS (including Git Bash)

source venv/bin/activate

First-time use may require temporarily releasing the execution policy:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
venv\Scripts\Activate.ps1

Windows - CMD

venv\Scripts\activate.bat

The sign of successful activation is: A virtual environment name enclosed in parentheses will appear in front of the terminal prompt, for example:

(venv) user@MacBook-Pro my_blog_project %

The whole process of daily use

1. Install packages in a virtual environment

Recommendedpython -m pipThis way of writing can effectively avoid confusion between global pip and virtual environment pip:

python -m pip install requests django

You can also write directlypip install requests django, but only if the environment has been activated.

2. View installed packages

Check what libraries are in the virtual environment at any time:

pip list

3. Export dependency list (necessary for collaboration/deployment)

Freeze the names and exact versions of all packages in the current environment torequirements.txtIn the file:

pip freeze > requirements.txt

Example of file content:

asgiref==3.8.1
django==5.0.6
requests==2.32.3
urllib3==2.2.1

4. Rebuild the environment from the dependency list

After getting someone else's project or changing to a new computer, you can regain a completely consistent operating environment in just three steps:

  1. Enter the project directory
  2. Create and activate a new virtual environment
  3. Install all dependencies with one click:
    python -m pip install -r requirements.txt

5. Exit the virtual environment

When the work is completed and you want to return to the global environment, enter:

deactivate

Advanced tips and best practices

  • One Project, One Dedicated Environment – No matter how small your project is, it deserves its own virtual environment.
  • Don't upload the virtual environment folder to Git - Putvenv/(or.venv/) write.gitignore. The virtual environment is large and contains system paths, so there is no point in moving it around.
  • Timely updatesrequirements.txt – Remember to re-execute every time you install or uninstall the packagepip freeze
  • Create by specifying Python version – If the project strictly requires Python 3.10, you can create it directly like this:
    python3.10 -m venv venv
  • Give a custom alias to the virtual environment – When encountering multiple environments, you can distinguish them at a glance:
    python -m venv venv --prompt "my_blog"

After activation, the prompt will appear as(my_blog)

🧩 Unpopular but useful function

Inherit the globally installed large package

If you have 10GB of PyTorch installed globally and don’t want to copy it in each project, you can use this parameter:

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

⚠️ Use with caution! Version changes in global packages may quietly affect your project.

Upgrade the Python version of the virtual environment

After the global Python is upgraded from 3.9 to 3.10, the existing virtual environment can be upgraded simultaneously with the following command:

python -m venv --upgrade venv

Troubleshooting common problems

❓ Activation failed?

  • Check path: Confirm that you are currently in the project root directory and the path to the activation script is consistent with the virtual environment directory name.
  • PowerShell Execution Limitation: Before using PowerShell for activation for the first time, be sure to executeSet-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
  • File Corruption: The simplest way - delete the directory of the current environment and re-python -m venvCreate one.

❓ Can’t find the package?

There is a high probability that I forgot to activate the virtual environment. usewhich python(Linux/macOS) orwhere python(Windows) View the path to the current Python interpreter. If the path does not point to thevenv/bin/pythonorvenv\Scripts\python.exe, then reactivate it quickly.


How to choose an alternative?

venvIt is an official built-in lightweight solution, but there are other good tools in the Python ecosystem:

ToolsFeatures
virtualenvThe predecessor of venv, it has richer functions and supports earlier Python versions, but requires additional installation.
pipenvOnce popular, it integrated virtual environment and dependency management, but community activity has declined in recent years.
poetryThe "all-rounder" for modern Python projects, integrating virtual environment, dependency management, and packaging.
condaThe first choice for scientific computing/machine learning. It can not only manage Python packages, but also install system-level dependencies (such as CUDA).

For most common Python projects,venvIt is completely sufficient: no additional installation or official ongoing maintenance is required, it is simple and reliable.