Virtual environments
Identify the active interpreter and isolate a project's installed dependencies.
On this page
The concept
A virtual environment gives a project its own installed-package directory. It avoids changing another project's dependency versions. Create one with python3 -m venv .venv. On Linux/macOS activate it with source .venv/bin/activate; on PowerShell use .venv\Scripts\Activate.ps1.
After activation, python -m pip uses pip associated with that interpreter. sys.executable shows which interpreter actually runs your code. Comparing sys.prefix and sys.base_prefix indicates whether the interpreter is in a virtual environment. Activation is a terminal convenience, not a Python statement.
Worked example
Extract the example files. From the python_from_zero directory, run the following command in a terminal. On Windows, use py in place of python3.
python3 06_files_and_projects/41_venv_and_dependencies/lesson.pyimport sys
print("interpreter:", sys.executable)
print("inside venv:", sys.prefix != sys.base_prefix)Trace the result
- The executable path identifies the interpreter, which may differ between machines.
- The prefix comparison reports True inside a virtual environment and False otherwise.
- No environment is created and no package is installed by lesson.py itself.
interpreter: <PYTHON>
inside venv: <VENV>Interpreter and directory paths depend on your machine.
Line-by-line walkthrough
Line 1: import sys
Load sys (interpreter information and command-line arguments). Importing makes these names available; it is not a call to every function in the module.
Line 3: print("interpreter:", sys.executable)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 4: print("inside venv:", sys.prefix != sys.base_prefix)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Common mistake
Do not commit .venv to Git or assume that copying it makes a portable environment. Recreate dependencies from project metadata.