A Python virtual environment is an isolated, self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.
1. Why virtual environment?
Imagine you have two projects on your computer:
- Project A requires
Django 2.2 - Project B requires
Django 3.0
If you install Django globally on your computer, you can only have one version installed at a time. Upgrading Django for Project B will break Project A.
Virtual environments solve this by giving each project its own isolated Python environment, completely separate from the system’s global Python packages.
2. venv module
Python 3 comes with a built-in module called venv which is used to create these virtual environments. You do not need to install it.
3. Create virtual environment
To create a virtual environment, open your terminal, navigate to your project folder, and run:
python -m venv myenv
(On Mac/Linux, you might need to use python3 -m venv myenv)
This creates a new folder called myenv inside your project directory. This folder contains a fresh copy of the Python interpreter and a blank slate for packages.
4. Activate / deactivate
Before you can use the virtual environment, you need to activate it. The activation command differs depending on your operating system.
On Windows
myenv\Scripts\activate.bat
If you are using PowerShell on Windows:
myenv\Scripts\Activate.ps1
On Mac and Linux
source myenv/bin/activate
Once activated, you will see (myenv) prepended to your command prompt, indicating that you are now operating inside the virtual environment.
Deactivate
To leave the virtual environment and return to the global system environment, simply type:
deactivate
5. Install packages in venv
When the virtual environment is active, any packages you install via PIP will be placed inside the myenv folder, rather than your global system.
# Ensure the environment is active (you see (myenv) in the terminal)
pip install requests
pip install django==3.0
To see which packages are installed exclusively in this environment, use:
pip freeze
It is a best practice to generate a requirements.txt file from this isolated environment to ensure your project can be reproduced perfectly on another machine.
Discussion
Loading comments...