Introduction
A virtual environment is a self-contained directory that isolates your Python projects and their dependencies. This prevents conflicts between different projects and ensures a consistent development environment. Using virtual environments in Visual Studio Code is a best practice for Python developers.
Step-by-Step Guide
- Activate the virtual environment:
- For environments created with virtualenv:
source venv/bin/activate
- For environments created with conda:
conda activate myenv
- Open Visual Studio Code.
- Set the Python interpreter:
- Open the command palette (Ctrl+Shift+P on Windows/Linux, Cmd+Shift+P on macOS).
- Type “Python: Select Interpreter” and press Enter.
- Select the interpreter associated with your activated virtual environment.
- Verify:
- Open a Python file in Visual Studio Code.
- Check the status bar at the bottom right corner. It should indicate that the Python interpreter is set to your virtual environment.
Additional Tips
- Switching between virtual environments: Use the “Python: Select Interpreter” command to easily switch between different virtual environments.
- Setting the Python interpreter for a specific project: Add the following line to your project’s settings.json file:
"python.pythonPath": "/path/to/your/python/interpreter"