Skip to main content

Python Cheatsheet

Quick reference for environment tools (uv/venv), standard library patterns, pyserial, and pytest.

Environments & Packages (uv / venv)​

# With uv (recommended)
uv init my-tool
uv add pyserial pytest
uv run python main.py
uv run pytest

# With standard venv
python -m venv .venv
source .venv/bin/activate # Linux/macOS
.venv\Scripts\Activate.ps1 # Windows PowerShell
pip install -r requirements.txt

Files & Paths (pathlib)​

from pathlib import Path

root = Path("logs")
root.mkdir(parents=True, exist_ok=True)

for file in root.glob("*.log"):
text = file.read_text(encoding="utf-8")
print(file.stem, len(text))

Running System Commands (subprocess)​

import subprocess

res = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
check=True,
)
print(res.stdout.strip())

Minimal CLI (argparse)​

import argparse

parser = argparse.ArgumentParser(description="Flash helper")
parser.add_argument("port", help="Serial port (e.g. COM5 or /dev/ttyUSB0)")
parser.add_argument("-b", "--baud", type=int, default=115200)
args = parser.parse_args()

Serial Communication (pyserial)​

import serial

with serial.Serial("COM5", baudrate=115200, timeout=1) as ser:
ser.write(b"version\r\n")
line = ser.readline().decode("utf-8", errors="replace").strip()
print(line)

Testing (pytest) & Linting (ruff)​

pytest -q # Run tests quietly
pytest -k "serial" -v # Run tests matching a keyword
ruff check . # Lint code
ruff format . # Format code

References​