Sahaj.blogs
27 Oct 2023 · StudyPhase 1 · Python

Python · venv and pip

Isolating project dependencies with venv, installing with pip, and pinning versions in requirements.txt.

I closed the Python phase with tooling. Different projects need different library versions, and installing everything globally ends in conflicts. A virtual environment is a folder with its own python and its own site-packages.

python -m venv .venv            # create
.venv\Scripts\activate          # Windows (source .venv/bin/activate on Linux/macOS)
python -m pip install numpy     # install into the venv only
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt   # rebuild elsewhere
deactivate

Habits I’m keeping:

  • Run pip as python -m pip, so it is always the pip of the active interpreter.
  • Add .venv/ to .gitignore and commit requirements.txt instead.

The snippet below checks, from inside Python, whether it is running in a venv.

import sys, venv, tempfile, pathlib, subprocess

print("in a venv:", sys.prefix != sys.base_prefix)

env_dir = pathlib.Path(tempfile.mkdtemp()) / "demo-env"
venv.create(env_dir, with_pip=False)
py = env_dir / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
out = subprocess.run([str(py), "-c", "import sys; print(sys.prefix != sys.base_prefix)"],
                     capture_output=True, text=True)
print("new env created:", py.exists(), "| its python is in a venv:", out.stdout.strip())

Output:

in a venv: True
new env created: True | its python is in a venv: True

With this, phase 1 is done. Next up is C++.

#python#tooling

Sources

  1. Virtual Environments and Packages — Python Software Foundation
  2. venv: creation of virtual environments — Python Software Foundation
  3. pip user guide — Python Packaging Authority
  4. Installing packages using pip and virtual environments — Python Packaging Authority