Using `venv` in Python
A Python virtual environment isolates a project’s installed packages from the system Python environment and from other projects. This helps prevent dependency conflicts and makes development environments easier to reproduce.
Create a Virtual Environment
From the project directory:
python3 -m venv .venv.venv is a common directory name because many editors recognize it automatically. You can use another name if your project has a different convention.
On some Debian or Ubuntu installations, the venv support package may need to be installed separately:
sudo apt install python3-venvActivate It on Linux or macOS
source .venv/bin/activateYour shell prompt often changes to show that the environment is active.
Activate It on Windows
PowerShell:
.\.venv\Scripts\Activate.ps1Command Prompt:
.venv\Scripts\activate.batActivation is convenient, but not technically required. You can always invoke the environment’s Python executable directly.
Install Packages
After activation:
python -m pip install requestsUsing python -m pip makes it explicit that pip belongs to the active Python interpreter.
Check installed packages:
python -m pip listRecord Dependencies
For simple projects using a requirements.txt workflow:
python -m pip freeze > requirements.txtAnother environment can install them with:
python -m pip install -r requirements.txtFor libraries and modern applications, dependency metadata is often maintained in pyproject.toml by tools such as pip, uv, Poetry, or PDM. A virtual environment remains useful regardless of which dependency-management tool creates or manages it.
Deactivate the Environment
deactivateThis restores the shell’s previous Python path.
Do Not Commit the Environment Directory
Add the environment directory to .gitignore:
.venv/
Commit dependency declarations such as pyproject.toml, lock files where appropriate, or requirements.txt instead of committing installed package files.
Recreate an Environment
Virtual environments are disposable. If one becomes inconsistent, remove it and recreate it from declared dependencies:
rm -rf .venv
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txtOnly run destructive commands such as rm -rf after confirming that the path is correct.
Conclusion
Use one virtual environment per Python project unless your tooling has a specific reason to do otherwise. Keep the environment directory out of version control and make dependency declarations the reproducible source of truth.