Tools › Cheat sheets › Programming & Tooling › Python (venv & pip)
🐍

Python (venv & pip) cheat sheet

Everyday Python tooling. Always use a virtual environment per project so dependencies do not clash. On Windows, activate with .venv\Scripts\activate instead of the source command.

Click any command to copy it.

Virtual environments

CommandWhat it does
python3 -m venv .venvCreate a virtual environment in .venv.
source .venv/bin/activateActivate it (Linux/macOS).
.venv\Scripts\activateActivate it (Windows).
deactivateLeave the environment.
which pythonConfirm you are using the environment's Python.
rm -rf .venvDestructive: Delete the environment; recreate it from requirements.txt.
python3 -m venv --upgrade-deps .venvUpgrade pip inside an environment.

pip

CommandWhat it does
pip install packageInstall a package.
pip install package==1.2.3Install an exact version.
pip install -U packageUpgrade a package.
pip install -r requirements.txtInstall everything in a requirements file.
pip freeze > requirements.txtSave the installed packages and versions.
pip list --outdatedShow packages with newer versions.
pip show packageShow details and installed location.
pip uninstall packageRemove a package.
pip install -e .Install the current project in editable mode.
pip cache purgeClear pip's download cache.
python3 -m pip install --upgrade pipUpgrade pip itself.

Run things

CommandWhat it does
python3 script.pyRun a script.
python3 -c "print(2 + 2)"Run a one-line command.
python3 -m http.server 8000Serve the current directory over HTTP on port 8000.
python3 -m json.tool data.jsonPretty-print a JSON file.
python3 -m pdb script.pyDebug with the built-in debugger.
python3 -m timeit 'sum(range(1000))'Time a small snippet.
python3 -m py_compile file.pyCheck a file for syntax errors.
PYTHONPATH=. python3 script.pyAdd the current folder to the import path.

Testing

CommandWhat it does
pytestRun all tests.
pytest -xStop at the first failure.
pytest -k nameRun tests whose names match.
pytest path/to/test_file.py::test_nameRun one test.
pytest -vVerbose output.
pytest --lfRe-run only the tests that failed last time.
pytest --cov=packageMeasure coverage (needs pytest-cov).

Tools

CommandWhat it does
pipx install toolInstall a command-line tool in its own isolated environment.
python3 --versionShow the Python version.
pip config listShow pip configuration.
python3 -m ensurepip --upgradeInstall pip where it is missing.

Frequently asked questions

Why should I use a virtual environment?

It keeps each project's dependencies separate, so upgrading a library for one project cannot break another, and it avoids modifying system Python packages.

What does 'externally-managed-environment' mean?

Recent Linux distributions block pip from changing the system Python. Create a virtual environment (python3 -m venv) or use pipx for command-line tools.

More Programming & Tooling cheat sheets

📗 npm🧩 Regular expressionsAll Programming & Tooling cheat sheets →
Copied to clipboard