Python’s platform module retrieves information about the runtime environment. import platform. system: platform.system() → "Windows", "Linux", "Darwin" (macOS), "Java". node: platform.node() → hostname. release: platform.release() → OS release (e.g., "22.04" on Ubuntu, "11" on Windows). version: platform.version() → detailed version string. machine: platform.machine() → architecture string ("x86_64", "arm64", "aarch64"). processor: platform.processor() → CPU brand string (may be empty on some systems). python_version: platform.python_version() → "3.12.0". python_version_tuple: platform.python_version_tuple() → ("3", "12", "0"). python_implementation: platform.python_implementation() → "CPython", "PyPy", "Jython". python_build: platform.python_build() → (build_no, date). python_compiler: platform.python_compiler() → compiler used. uname: platform.uname() → uname_result(system, node, release, version, machine, processor). architecture: platform.architecture() → ("64bit", "ELF"). mac_ver: platform.mac_ver() → (release, versioninfo, machine). win32_ver: platform.win32_ver() → (release, version, csd, ptype). freedesktop_os_release: platform.freedesktop_os_release() → dict from /etc/os-release (Linux 3.10+). Claude Code generates system info reporters, platform guards, environment validators, and cross-platform compatibility checkers.
CLAUDE.md for platform
## platform Stack
- Stdlib: import platform
- OS: platform.system() # "Linux" | "Darwin" | "Windows"
- Arch: platform.machine() # "x86_64" | "arm64" | "aarch64"
- Python: platform.python_version() # "3.12.0"
- All: platform.uname() # namedtuple with all fields
- Linux ID: platform.freedesktop_os_release()["ID"] # "ubuntu", "fedora", etc.
- Guard: if platform.system() != "Linux": raise RuntimeError(...)
platform Environment Detection Pipeline
# app/platutil.py — system info, platform guards, env validator, version checks
from __future__ import annotations
import os
import platform
import struct
import sys
from dataclasses import dataclass
from typing import Any
# ─────────────────────────────────────────────────────────────────────────────
# 1. System info snapshot
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class SystemInfo:
os_name: str
os_release: str
os_version: str
hostname: str
machine: str
processor: str
python_version: str
python_impl: str
python_build: str
python_compiler: str
bits: str # "64bit" or "32bit"
is_64bit: bool
is_linux: bool
is_macos: bool
is_windows: bool
linux_id: str # "" on non-Linux
linux_version_id: str # "" on non-Linux
macos_version: str # "" on non-macOS
@classmethod
def collect(cls) -> "SystemInfo":
"""
Collect all platform information into a structured snapshot.
Example:
info = SystemInfo.collect()
print(info.os_name, info.machine, info.python_version)
"""
uname = platform.uname()
arch = platform.architecture()
sys_name = platform.system()
bits = arch[0]
linux_id = linux_vid = ""
if sys_name == "Linux":
try:
rel = platform.freedesktop_os_release()
linux_id = rel.get("ID", "")
linux_vid = rel.get("VERSION_ID", "")
except (OSError, AttributeError):
pass
macos_ver = ""
if sys_name == "Darwin":
macos_ver = platform.mac_ver()[0]
return cls(
os_name=sys_name,
os_release=uname.release,
os_version=uname.version,
hostname=uname.node,
machine=uname.machine,
processor=uname.processor,
python_version=platform.python_version(),
python_impl=platform.python_implementation(),
python_build=f"{platform.python_build()[0]} {platform.python_build()[1]}",
python_compiler=platform.python_compiler(),
bits=bits,
is_64bit=(bits == "64bit"),
is_linux=(sys_name == "Linux"),
is_macos=(sys_name == "Darwin"),
is_windows=(sys_name == "Windows"),
linux_id=linux_id,
linux_version_id=linux_vid,
macos_version=macos_ver,
)
def to_dict(self) -> dict[str, Any]:
return {
"os": f"{self.os_name} {self.os_release}",
"hostname": self.hostname,
"arch": f"{self.machine} ({self.bits})",
"processor": self.processor,
"python": f"{self.python_impl} {self.python_version}",
"build": self.python_build,
"linux_distro": f"{self.linux_id} {self.linux_version_id}".strip() or None,
"macos_version": self.macos_version or None,
}
def report(self) -> str:
d = self.to_dict()
lines = ["System Information:"]
for k, v in d.items():
if v is not None:
lines.append(f" {k:20s}: {v}")
return "\n".join(lines)
# ─────────────────────────────────────────────────────────────────────────────
# 2. Platform guards
# ─────────────────────────────────────────────────────────────────────────────
def require_platform(*systems: str) -> None:
"""
Raise RuntimeError if current OS is not in the allowed list.
Example:
require_platform("Linux", "Darwin") # fails on Windows
"""
current = platform.system()
if current not in systems:
raise RuntimeError(
f"This code requires {' or '.join(systems)}, "
f"but is running on {current!r}."
)
def require_64bit() -> None:
"""Raise RuntimeError if Python is running in 32-bit mode."""
bits = platform.architecture()[0]
if bits != "64bit":
raise RuntimeError(f"64-bit Python required; current is {bits}.")
def require_python(min_version: tuple[int, int]) -> None:
"""
Raise RuntimeError if the running Python version is below min_version.
Example:
require_python((3, 10)) # fails on Python 3.9
"""
current = sys.version_info[:2]
if current < min_version:
raise RuntimeError(
f"Python {'.'.join(map(str, min_version))}+ required; "
f"running {platform.python_version()}."
)
def require_cpython() -> None:
"""Raise RuntimeError if not running on CPython."""
impl = platform.python_implementation()
if impl != "CPython":
raise RuntimeError(f"CPython required; running {impl}.")
# ─────────────────────────────────────────────────────────────────────────────
# 3. Conditional platform dispatch
# ─────────────────────────────────────────────────────────────────────────────
_SYSTEM = platform.system()
IS_LINUX = _SYSTEM == "Linux"
IS_MACOS = _SYSTEM == "Darwin"
IS_WINDOWS = _SYSTEM == "Windows"
IS_64BIT = platform.architecture()[0] == "64bit"
IS_ARM = platform.machine().lower() in ("arm64", "aarch64", "armv7l")
def temp_dir() -> str:
"""
Return the system temporary directory path, platform-appropriate.
Example:
path = os.path.join(temp_dir(), "myapp_cache")
"""
import tempfile
return tempfile.gettempdir()
def config_dir(app_name: str) -> str:
"""
Return the platform-appropriate user config directory.
- Linux/macOS: ~/.config/app_name
- Windows: %APPDATA%/app_name
Example:
cfg = config_dir("myapp") # "/home/user/.config/myapp"
"""
if IS_WINDOWS:
base = os.environ.get("APPDATA", os.path.expanduser("~"))
else:
base = os.path.join(os.path.expanduser("~"), ".config")
return os.path.join(base, app_name)
def cache_dir(app_name: str) -> str:
"""
Return the platform-appropriate user cache directory.
- Linux: ~/.cache/app_name
- macOS: ~/Library/Caches/app_name
- Windows: %LOCALAPPDATA%/app_name/cache
Example:
cache = cache_dir("myapp")
"""
if IS_WINDOWS:
base = os.environ.get("LOCALAPPDATA", os.path.expanduser("~"))
return os.path.join(base, app_name, "cache")
elif IS_MACOS:
return os.path.join(os.path.expanduser("~"), "Library", "Caches", app_name)
else:
return os.path.join(os.path.expanduser("~"), ".cache", app_name)
def data_dir(app_name: str) -> str:
"""
Return the platform-appropriate user data directory.
- Linux: ~/.local/share/app_name
- macOS: ~/Library/Application Support/app_name
- Windows: %APPDATA%/app_name/data
Example:
data = data_dir("myapp")
"""
if IS_WINDOWS:
base = os.environ.get("APPDATA", os.path.expanduser("~"))
return os.path.join(base, app_name, "data")
elif IS_MACOS:
return os.path.join(os.path.expanduser("~"), "Library", "Application Support", app_name)
else:
return os.path.join(os.path.expanduser("~"), ".local", "share", app_name)
def shared_lib_ext() -> str:
"""Return the platform shared library extension: .so / .dylib / .dll."""
if IS_WINDOWS:
return ".dll"
elif IS_MACOS:
return ".dylib"
else:
return ".so"
def executable_ext() -> str:
"""Return the executable extension: "" on POSIX, ".exe" on Windows."""
return ".exe" if IS_WINDOWS else ""
def native_line_ending() -> str:
"""Return the platform line ending: '\\r\\n' on Windows, '\\n' elsewhere."""
return "\r\n" if IS_WINDOWS else "\n"
# ─────────────────────────────────────────────────────────────────────────────
# 4. Python version utilities
# ─────────────────────────────────────────────────────────────────────────────
def python_version_tuple() -> tuple[int, int, int]:
"""Return (major, minor, micro) as ints."""
t = platform.python_version_tuple()
return int(t[0]), int(t[1]), int(t[2])
def is_python_at_least(major: int, minor: int = 0, micro: int = 0) -> bool:
"""
Return True if running Python >= (major, minor, micro).
Example:
if is_python_at_least(3, 11):
# use tomllib
import tomllib
"""
return sys.version_info >= (major, minor, micro)
def python_feature_flags() -> dict[str, bool]:
"""
Return a dict of available Python features detected at runtime.
Example:
flags = python_feature_flags()
if flags["tomllib"]:
import tomllib
"""
flags: dict[str, bool] = {
"tomllib": is_python_at_least(3, 11),
"exception_notes": is_python_at_least(3, 11),
"match_statement": is_python_at_least(3, 10),
"zoneinfo": is_python_at_least(3, 9),
"asyncio_timeout": is_python_at_least(3, 11),
"type_alias": is_python_at_least(3, 12),
"walrus": is_python_at_least(3, 8),
"dict_union": is_python_at_least(3, 9),
"is_pypy": platform.python_implementation() == "PyPy",
"is_64bit": IS_64BIT,
}
return flags
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("=== platform demo ===")
print("\n--- SystemInfo ---")
info = SystemInfo.collect()
print(info.report())
print("\n--- to_dict ---")
import json
d = {k: v for k, v in info.to_dict().items() if v is not None}
print(json.dumps(d, indent=2))
print("\n--- platform guards ---")
try:
require_python((3, 8))
print(" require_python(3.8): ok")
except RuntimeError as e:
print(f" {e}")
try:
require_64bit()
print(" require_64bit: ok")
except RuntimeError as e:
print(f" {e}")
print("\n--- platform constants ---")
print(f" IS_LINUX={IS_LINUX} IS_MACOS={IS_MACOS} IS_WINDOWS={IS_WINDOWS}")
print(f" IS_64BIT={IS_64BIT} IS_ARM={IS_ARM}")
print("\n--- directory helpers ---")
print(f" temp_dir: {temp_dir()}")
print(f" config_dir: {config_dir('myapp')}")
print(f" cache_dir: {cache_dir('myapp')}")
print(f" data_dir: {data_dir('myapp')}")
print(f" shared_lib: {shared_lib_ext()}")
print(f" exe_ext: {executable_ext()!r}")
print(f" line_end: {native_line_ending()!r}")
print("\n--- python version ---")
print(f" version tuple: {python_version_tuple()}")
print(f" >= 3.10: {is_python_at_least(3, 10)}")
print("\n--- python_feature_flags ---")
flags = python_feature_flags()
for k, v in flags.items():
print(f" {k:25s}: {v}")
print("\n=== done ===")
For the sys alternative — sys.platform returns "linux", "darwin", "win32", or "cygwin" as a lowercase string without version info; sys.version_info provides (major, minor, micro, releaselevel, serial) as a structured tuple; platform wraps these plus OS-level calls (uname, /etc/os-release, mac_ver) to provide the full picture — use sys.platform for quick OS-type checks in library code where a lightweight comparison is all that’s needed; use platform when you need version strings, CPU architecture, hostname, distro identity, or structured uname data. For the distro alternative — the distro PyPI package specializes in Linux distribution identification, providing distro.id(), distro.name(), distro.version(), distro.codename() with broader coverage than platform.freedesktop_os_release() (falls back to parsing multiple files and /etc/lsb-release); platform.freedesktop_os_release() covers all modern Linux systems (systemd-based) and requires no third-party install — use distro in tools that must support older non-systemd Linux distributions or that need extensive distro metadata; use platform.freedesktop_os_release() for modern systems (Ubuntu 18.04+, Fedora 28+, Debian 10+, RHEL 7+). The Claude Skills 360 bundle includes platform skill sets covering SystemInfo dataclass with collect()/to_dict()/report(), require_platform()/require_64bit()/require_python()/require_cpython() guards, IS_LINUX/IS_MACOS/IS_WINDOWS/IS_64BIT/IS_ARM constants, config_dir()/cache_dir()/data_dir()/shared_lib_ext()/executable_ext() cross-platform path helpers, and python_feature_flags()/is_python_at_least() version utilities. Start with the free tier to try cross-platform detection and platform pipeline code generation.