How to Create a Python Virtual Environment
Create an isolated Python virtual environment with venv, activate it on Mac, Linux, or Windows, install packages into it, and deactivate when done.
You have a Python project and want its packages kept separate from everything else on the machine. The venv module ships with Python 3, so nothing needs to be installed first.
Create the environment
Open a terminal in the project folder and run:
python3 -m venv .venv
This creates a .venv folder containing a private copy of the Python interpreter and its own site-packages directory. The name .venv is a convention, but any folder name works.
On Windows, use python -m venv .venv.
Activate the environment
source .venv/bin/activate
On Windows (Command Prompt or PowerShell): .venv\Scripts\activate
The prompt changes to show the environment name:
(.venv) $
While the environment is active, python and pip point at the copies inside .venv, not the system versions.
Install packages
pip install requests
Packages land inside .venv and are invisible to other projects. Check what is installed at any time with pip list.
Deactivate when finished
deactivate
The prompt returns to normal and python refers to the system interpreter again. The environment stays on disk. Reactivate it any time with the same source command.
Keep it out of version control. Add .venv/ to the project's .gitignore. The folder is large and specific to one machine. To record what the project depends on instead, run pip freeze > requirements.txt while the environment is active. Anyone can then rebuild the same environment with pip install -r requirements.txt.
If the venv module is missing. On Debian and Ubuntu the module is packaged separately. Install it with sudo apt install python3-venv and run the create command again.
More Coding how-tos
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Create a New Git Branch
- How to Install Node.js with nvm
- How to Make a Script Executable in the Terminal
- How to Print Hello World in JavaScript
- How to Print Hello World in Python
- How to Run a Local Web Server in One Command
- How to Undo the Last Git Commit