A Simple Guide to Python Virtual Environments
A virtual environment (venv) is an isolated copy of the Python interpreter, along with its own set of installed packages, dedicated to a single project, which could solve the two critical problems, dependency conflicts and system integrity.
How to Set Up a Virtual Environment (Ubuntu/VS Code)
Setting up a virtual environment involves three quick steps: installation, creation, and configuration.
Step 1: Install the venv Module (If Needed)
On Ubuntu, the venv module—the tool used to create virtual environments—must often be installed separately via the system package manager.
- Update the package list:
sudo apt update - Install the package for the specific Python version (e.g., Python 3.12):
sudo apt install python3.12-venv
Step 2: Create and Activate the Environment
Once the module is installed, the environment can be created within the project’s root directory.
- Navigate to the project folder in the terminal:
cd ~/path/to/project - Create the environment (naming the folder
venvis the convention):python3 -m venv venv - Activate the environment in the terminal session:The terminal prompt will change to include
source venv/bin/activate(venv), signifying that the isolated environment is active. All subsequentpipinstalls will go directly into this isolated project folder.
Step 3: Configure VS Code
To ensure the code editor knows where to find the installed packages (like Selenium), the correct interpreter must be selected in VS Code.
- In VS Code, open the Command Palette by pressing Ctrl + Shift + P.
- Type “Python: Select Interpreter” and press Enter.
- Select the interpreter path that points to the environment created, typically labeled as:
Python 3.12.3 ('venv': venv).
Once selected, the VS Code Python extension automatically manages the environment. Any Integrated Terminal opened within VS Code will use the correct interpreter, eliminating manual activation and resolving “Import could not be resolved” errors.