Real programs use third-party packages, and each project may need different versions of the same package. Installing everything in the system Python ends in conflicts. The solution is one virtual environment per project.
# Terminal (not Python code)
python -m venv .venv # creates the environment in the .venv folder
source .venv/bin/activate # Linux and macOS
.venv\Scripts\activate # Windows
pip install requests # installs a package only in this environment
pip freeze > requirements.txt # saves the installed versions
pip install -r requirements.txt # recreates the environment on another computer
deactivate # leaves the environment
import sys
print(sys.prefix != sys.base_prefix) # True inside a virtual environment; False outside
print(sys.version_info >= (3, 8)) # True
# A virtual environment is just a folder with its own copy of "python" and "site-packages".
# "pip list" shows what is installed in the active environment.
venvcomes with Python. The environment lives in a folder (usually called.venv) that is not committed to the repository.pipis the package installer.pip install name==1.2.3pins a version;pip install --upgrade nameupdates it.requirements.txtlists the project's packages and versions. Whoever clones the project creates their own environment and runspip install -r requirements.txt.- For projects that are published,
pyproject.tomldescribes the package and its dependencies (it is the TOML format you saw in the data formats lesson). - Before installing anything, check that the right environment is active: its name appears in parentheses in the terminal.