Using Venv for Virtual Environments
This is a brief tutorial on how to use venv to create and manage python virtual environments.
Managing Python Environments with venv
This tutorial covers how to:
- Create a virtual environment (from terminal and Positron)
- Activate and deactivate it
- Create a
requirements.txt - Recreate an environment from
requirements.txt
Why Virtual Environments?
In R, each project can effectively have its own package library. In Python, we achieve this using virtual environments.
A virtual environment:
- Is isolated from your system Python
- Has its own installed packages
- Prevents version conflicts across projects
Virtual environments are particularly useful when working with smaller community- and single-maintainer packages which might rely on earlier versions of common libraries (numpy, pandas, etc).
1. Create a Virtual Environment
From the Terminal
Navigate to your project folder:
Create a virtual environment:
This creates a folder called .venv inside your project.
If you have multiple Python versions
You may need:
or on Windows:
From Positron
- Open your project.
- Open the Terminal pane.
- Run:
Select the interpreter:
- Command palette → “Python: Select Interpreter”
- Choose the interpreter inside
.venv
- Command palette → “Python: Select Interpreter”
Positron will now use that environment for the project.
OR
Open your project.
Open Command pane (ctrl+shift+p or cmd+shift+p)
Select
Python: Create Environment
Select
venv- Positron will create a virtual environment
.venvfor you
- Positron will create a virtual environment
2. Activate and Deactivate a Virtual Environment
Activate
macOS / Linux
Windows (PowerShell)
Windows (Command Prompt)
When activated, your terminal will show:
(.venv) $
Positron
Select the interpreter:
- Command palette → “Python: Select Interpreter”
Choose the interpreter inside
.venv
Deactivate
From any system:
This returns you to your global Python.
3. Create a requirements.txt
After installing packages inside your virtual environment:
Freeze the environment:
This creates a file like:
numpy==1.26.4
pandas==2.2.1
scikit-learn==1.4.0
This captures exact versions — similar to renv::snapshot() in R.
4. Recreate an Environment from requirements.txt
If you clone a repo and it has a requirements.txt file:
Step 1: Create a new virtual environment
Step 2: Activate it
(macOS/Linux)
(Windows PowerShell)
Step 3: Install from requirements
This installs all specified packages and versions.
Equivalent idea in R:
renv::restore()≈pip install -r requirements.txt
Recommended Project Structure
project/
│
├── .venv/
├── requirements.txt
├── analysis.py
└── README.md
If using git, add
.venv/to.gitignoreso it is not committed!