To create a virtual environment for Python in VS Code, follow these step-by-step instructions:
Step 1: Open VS Code and Open a Folder
1. Open VS Code.
2. Click on File → Open Folder and choose or create a new project folder.
o This ensures that the virtual environment is created inside the project folder.
Step 2: Open the Integrated Terminal
Open the terminal in VS Code by pressing:
o Ctrl + ` (backtick) on Windows/Linux
o Cmd + ` on macOS
Make sure you're inside your project folder.
Step 3: Create the Virtual Environment
For Windows (Command Prompt or PowerShell)
Run:
python -m venv venv
For macOS/Linux (Terminal)
Run:
python3 -m venv venv
🔹 Note: Replace venv with any name you want for your virtual environment.
Step 4: Activate the Virtual Environment
After creating the virtual environment, activate it.
On Windows
Command Prompt (cmd)
venv\Scripts\activate
PowerShell
venv\Scripts\Activate.ps1
On macOS/Linux
source venv/bin/activate
After activation, you’ll see (venv) in the terminal, indicating that the virtual environment is
active.
Step 5: Select the Virtual Environment in VS Code
1. Press Ctrl + Shift + P (or Cmd + Shift + P on macOS).
2. Type "Python: Select Interpreter" and select it.
3. Choose the interpreter inside the venv folder.
o It will look like:
Windows: venv\Scripts\python.exe
Mac/Linux: venv/bin/python
Step 6: Install Required Packages
Once activated, install dependencies using:
pip install package_name
Or if you have a requirements.txt file:
pip install -r requirements.txt
Step 7: Verify the Virtual Environment
To confirm that your virtual environment is working, run:
python --version
You should see the Python version from your virtual environment.
Common Issues & Fixes
1. "venv is not recognized"
Run:
python -m ensurepip --default-pip
2. "Activate command not found"
If using PowerShell, run:
Set-ExecutionPolicy Unrestricted -Scope Process
3. Virtual Environment Not Showing in VS Code
Manually set the interpreter:
o File → Preferences → Settings.
o Search for python.defaultInterpreterPath.
o Set it to:
o "python.defaultInterpreterPath":
"your_project_path/venv/bin/python"
✅ Your virtual environment is now ready! 🚀
Let me know if you need any help!