Claude Code for platform: System Information in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for platform: System Information in Python
AI

Claude Code for platform: System Information in Python

Published: August 7, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free