Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

33 matches
Automation & scripting easy

How to Kill Zombie Processes Matching a Name in Python

Scans running processes with ps, finds zombies whose command name matches a pattern, and attempts to kill them with SIGKILL.

subprocess process automation
Python
import subprocess
import re
import signal


def find_zombies(name_pattern):
    """Find PIDs of zombie processes matching the given pattern."""
    result = subprocess.run(["ps", "-eo", "pid,stat,comm"], capture_output=True, text=True)
    zombies = []
    for line in result.stdout.splitlines()[1:]:  # Skip header
   …
10 0 Open
Automation & scripting easy

Parse WHOIS Data with Python Regex

Extract domain registration fields from a mock WHOIS record using regex and compute days until expiration.

whois regex parsing
Python
import re
from datetime import datetime


def parse_whois(whois_text: str) -> dict:
    """Extract key registration fields from a mock WHOIS record."""
    patterns = {
        "domain": r"Domain Name:\s*(.+)",
        "registrar": r"Registrar:\s*(.+)",
        "creation_date": r"Creation Date:\s*(.+)",
        "expir…
12 0 Open
Automation & scripting easy

Parse nginx access log top IPs in Python

Reads an nginx access log line by line, extracts the client IP, and returns the most frequent IPs using a regex and Counter.

nginx log parsing regex
Python
import re
from collections import Counter

def top_ips(log_file, n=10):
    ip_pattern = re.compile(r'^(\S+)')
    ip_counts = Counter()

    with open(log_file, 'r') as f:
        for line in f:
            match = ip_pattern.match(line)
            if match:
                ip_counts[match.group(1)] += 1

    return…
14 0 Open
Automation & scripting easy

Pin Python package versions in requirements.txt

Pin package versions in requirements.txt-style text by adding ==version when no specifier is present, while preserving existing version constraints and comments.

requirements automation versions
Python
import re
from pathlib import Path


def pin_versions(requirements_text: str) -> str:
    """
    Pin package versions in requirements.txt-style text.
    Adds ==version if no version specifier is present.
    Keeps existing specifiers (>=, <=, ~=, etc.) unchanged.
    """
    lines = requirements_text.strip().splitli…
14 0 Open
Data pipelines & processing easy

How to Hash Email Addresses in a PII Masking Pipeline in Python

Replaces every email address in a text string with its SHA-256 hash to protect personally identifiable information (PII).

pii hashing sha256
Python
import hashlib
import re

def hash_email(email: str) -> str:
    """Mask an email address by hashing it with SHA-256."""
    normalized = email.strip().lower()
    return hashlib.sha256(normalized.encode("utf-8")).hexdigest()

def mask_pii_emails(text: str) -> str:
    """Replace all email addresses in text with their…
14 0 Open
Git + Python easy

How to detect secrets in git history with Python

Scan a git history export file for common secret patterns using regex and Python.

git secrets security
Python
import re
from pathlib import Path


def scan_history_for_secrets(history_file: str) -> list:
    """Scan a git history export for potential secrets using regex patterns."""
    patterns = {
        "AWS Access Key": r"AKIA[0-9A-Z]{16}",
        "GitHub Token": r"gh[pousr]_[0-9A-Za-z]{36,255}",
        "Private Key": …
12 0 Open
API design & gRPC easy

How to Mock Content-Disposition and Extract Filename in Python

Parse and mock Content-Disposition headers in Python to extract filenames, handling both plain and RFC 5987 encoded values.

http mocking regex
Python
import os
from pathlib import Path
import re
from unittest.mock import patch

def get_filename_from_content_disposition(header_value):
    """
    Extract filename from a Content-Disposition header value.
    Supports both filename and filename* parameters (RFC 5987).
    """
    if not header_value:
        return No…
15 0 Open
Observability & SRE easy

Calculate Error Rate from Log Stream in Python

Parses a mock log stream to count errors and compute the error percentage using a rolling window of recent entries.

logging regex error-rate
Python
import re
from collections import deque

def error_rate_from_log_stream(message):
    log_pattern = r'^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (ERROR|INFO|DEBUG): (.*)$'
    recent_entries = deque(maxlen=100)
    error_count = 0
    total_count = 0

    for line in message.strip().split('\n'):
        match = re.mat…
15 0 Open
Observability & SRE easy

How to Parse Log Lines with Regex in Python

Extracts timestamp, log level, service name, and message from a log line using compiled regex named groups.

regex logging parsing
Python
import re

LOG_PATTERN = re.compile(
    r'^(?P<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) '
    r'\[(?P<level>\w+)\] '
    r'\((?P<service>[^)]+)\) '
    r'(?P<message>.*)$'
)

def parse_log_line(line: str) -> dict:
    match = LOG_PATTERN.match(line)
    if not match:
        return {"error": "invalid log format…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.