Chuyển tới nội dung chính

Python Cheatsheet

Tra cứu nhanh các lệnh quản lý môi trường (uv/venv), standard library, pyserial và pytest dùng hằng ngày.

Môi trường & Package (uv / venv)​

# Với uv (khuyến nghị)
uv init my-tool
uv add pyserial pytest
uv run python main.py
uv run pytest

# Với venv chuẩn
python -m venv .venv
source .venv/bin/activate # Linux/macOS
.venv\Scripts\Activate.ps1 # Windows PowerShell
pip install -r requirements.txt

File & Path (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))

Chạy lệnh hệ thống (subprocess)​

import subprocess

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

CLI đơn giản (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()

Giao tiếp Serial (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)

Kiểm thử (pytest) & Lint (ruff)​

pytest -q # Chạy test gọn
pytest -k "serial" -v # Chạy các test khớp tên
ruff check . # Kiểm tra lỗi lint
ruff format . # Format code tự động

Tham khảo​