Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Build a Network Ping Monitor in Python
A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.
import subprocess
import time
def ping_host(host, count=4):
"""Ping a host and return the results."""
try:
# Platform-independent ping command
cmd = ["ping", "-c", str(count), host]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return result.stdout, r…
Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.stri…
How to Detect Recently Installed Software in Python
Uses subprocess to call pip and parse package metadata to list recently installed Python packages.
import subprocess
import sys
from datetime import datetime, timedelta
def detect_recently_installed(days=7):
"""Detect recently installed software packages."""
recent_packages = []
cutoff_date = datetime.now() - timedelta(days=days)
try:
# For pip-installed packages (Python packages)
…
How to Monitor USB Device Connections in Python
A Python utility that monitors USB device connections and disconnections by comparing output of the lsusb command at regular intervals.
import time
import subprocess
import os
def get_usb_devices():
"""Return list of currently connected USB devices (Linux)."""
try:
result = subprocess.run(['lsusb'], capture_output=True, text=True, check=True)
return result.stdout.strip().split('\n')
except (subprocess.CalledProcessError, F…
How to Ping Multiple Hosts in Parallel with Python ThreadPoolExecutor
A parallel host-pinging script using ThreadPoolExecutor and subprocess to check connectivity across multiple addresses concurrently.
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
HOSTS = [
"google.com",
"github.com",
"stackoverflow.com",
"nonexistent.invalid",
"localhost",
]
def ping_host(host: str) -> str:
"""Ping a single host and return a status string."""
result = subp…
How to Run Tesseract OCR from Python with subprocess
This script uses Python's subprocess module to invoke the Tesseract OCR engine from the command line and return the extracted text.
import subprocess
def ocr_image(image_path):
command = ["tesseract", image_path, "stdout"]
result = subprocess.run(command, capture_output=True, text=True)
return result.stdout.strip()
if __name__ == "__main__":
# Stub: call the actual tesseract (must be installed)
text = ocr_image("sample.png")
…
Track Internet Connectivity and Downtime Automatically in Python
Monitors internet connectivity by pinging a remote host and logs any downtime events with timestamps and duration.
import time
import subprocess
from datetime import datetime
def check_internet(host="8.8.8.8", timeout=3):
"""Returns True if internet is reachable via ping."""
try:
subprocess.run(
["ping", "-c", "1", "-W", str(timeout), host],
capture_output=True,
timeout=timeout …
Find the Commit That Introduced a String in Git History Using Python
Use git log -S with Python subprocess to find the earliest commit that introduced a specific string across your repository history.
import subprocess
import sys
def find_introducing_commit(repo_path: str, search_string: str, file_glob: str = "*") -> str:
"""Find the first commit that introduced a given string in a git repository."""
result = subprocess.run(
["git", "-C", repo_path, "log", "--all", "--oneline", "-S", search_string…
How to Generate Release Notes from Git Commit Messages in Python
This script fetches recent Git commit messages using conventional commit prefixes (feat, fix, etc.), categorizes them, and prints formatted release notes with today's date.
import subprocess
import re
from datetime import datetime
def get_git_log(since_tag="HEAD~10", format_str="%s"):
"""Retrieve commit messages from git log."""
try:
result = subprocess.run(
["git", "log", f"--since={since_tag}", f"--format={format_str}"],
capture_output=True,
…
How to Get Current Git Branch Name in Python with Mock Subprocess
Mocks the subprocess call to reliably test the current git branch name retrieval using GitPython.
import subprocess
from unittest.mock import patch, MagicMock
from git import Repo
import os
def get_current_branch(repo_path="."):
"""Get the current branch name of a git repository."""
repo = Repo(repo_path)
return repo.active_branch.name
if __name__ == "__main__":
# Mock subprocess to control the…
How to Mock Git Pre-commit Hooks (black and ruff) in Python
Mock subprocess to test black and ruff pre-commit commands without actually running them, verifying exit codes.
import sys
import subprocess
from unittest.mock import patch
def run_hook(command: list[str]) -> int:
with patch("subprocess.run") as mock_run:
mock_run.return_value.returncode = 0
mock_run.return_value.stdout = f"Mocked: {' '.join(command)}"
result = subprocess.run(command, capture_output…
Show Blame Line Author with subprocess in Python
This Python script runs git blame --line-porcelain via subprocess and counts how many lines each author owns in a file.
import subprocess
from collections import Counter
def get_blame_authors(file_path):
"""Extract author names from git blame output using subprocess."""
result = subprocess.run(
["git", "blame", "--line-porcelain", file_path],
capture_output=True,
text=True,
check=True,
)
…
How to Mock subprocess.run for Black Formatter in Python
Use unittest.mock to simulate subprocess.run calls in a Python function that runs the Black formatter, allowing isolated testing without executing external commands.
import subprocess
from unittest.mock import Mock, patch
def run_black_formatter(file_path: str, check_only: bool = False) -> dict:
"""Run black formatter on a file via subprocess."""
cmd = ["black", "--check" if check_only else "-", file_path]
result = subprocess.run(cmd, capture_output=True, text=True)
…
How to Run an Integration Test with Docker Compose Mock in Python
Run a Python integration test against a docker-compose environment, using mocks to simulate service health and business logic responses.
import subprocess
import json
from typing import Dict
def run_integration_test() -> Dict[str, str]:
"""
Simulates an integration test against a docker-compose environment
using a mock service that returns canned responses.
"""
# Mock docker-compose environment check
env_ready = subprocess.run(…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.