A virtual environment gives one project its own tools.
Imagine two projects that need different versions of the same library. Installing everything globally can cause conflicts. A virtual environment gives each project its own set of installed Python packages.
PROJEKAT A
└── virtuelno okruženje A
└── njegove biblioteke
PROJEKAT B
└── virtuelno okruženje B
└── njegove bibliotekeEach project has its own toolbox. A virtual environment isolates project Python packages; it is not a security sandbox or a separate operating system.
The standard Python tool for this is venv. The environment usually lives in a local folder named .venv inside your project.
Two things to keep separate: Activating an environment changes which Python a terminal uses. Selecting an interpreter tells VS Code which Python to use for editing, running, and Python tooling. They are related, but not the same action.
python -m venv .venv
# On some macOS/Linux systems:
python3 -m venv .venvpython starts an interpreter, -m venv runs Python’s built-in environment module, and .venv is the folder it creates. Do not edit files inside .venv by hand.
macOS/Linux:
source .venv/bin/activate
Windows PowerShell:
.\.venv\Scripts\Activate.ps1
Windows Command Prompt:
.venv\Scripts\activate.bat
Leave an activated environment:
deactivateYou can also run the environment’s Python by its direct path without activating it. Use python -m pip when you want pip connected to the Python interpreter you chose.
python -m pip install requests
python -m pip list
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txtrequests is installed into the selected project environment. requirements.txt records distributions and versions that pip can install again; pip freeze also includes installed dependencies, not only packages you chose directly.
.venv/
__pycache__/
*.pycDo not send .venv to GitHub: it can be large, depends on the local system, and can be recreated. Keep requirements.txt with the project instead.
Choose the .venv interpreter in VS Code
- 1. Open the Command PaletteOpen the Command Palette in VS Code.
- 2. Choose Python: Select InterpreterFind and choose
Python: Select Interpreter. - 3. Select the Python inside .venvChoose the interpreter that belongs to your project’s
.venv, then check that VS Code shows it as selected.
Common virtual-environment problems
- python is not foundCheck that Python is installed. Try python3 on macOS/Linux; on Windows, use py where Python Launcher is available.
- A library is not foundCheck the activated environment, the VS Code interpreter, and which environment received the pip install.
- PowerShell blocks activationWindows execution-policy settings can block scripts. Do not permanently disable security protections; use a Command Prompt terminal or run the Python inside .venv directly instead.
- .venv is not visibleCheck that the folder was created. Some editor views can hide folders; check the interpreter selection again.
