Claude Code for posix: Python Direct POSIX Syscall Wrappers — Claude Skills 360 Blog
Blog / AI / Claude Code for posix: Python Direct POSIX Syscall Wrappers
AI

Claude Code for posix: Python Direct POSIX Syscall Wrappers

Published: October 25, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s posix module exposes the POSIX syscall surface that the os module is built on. import posix (Linux/macOS only; on POSIX systems os re-exports everything from posix transparently). Direct access: posix.stat(path)os.stat_result; posix.open(path, flags, mode=0o777) → fd int; posix.read(fd, n) → bytes; posix.write(fd, b) → int; posix.close(fd). Process: posix.fork() → 0 in child, child PID in parent; posix.execv(path, args); posix.execve(path, args, env); posix.waitpid(pid, options)(pid, status); posix.kill(pid, sig). Identity: posix.getpid(), posix.getppid(), posix.getuid(), posix.getgid(), posix.geteuid(), posix.getegid(), posix.getlogin(). Filesystem: posix.getcwd(), posix.chdir(path), posix.listdir(path), posix.mkdir(path, mode), posix.rmdir(path), posix.rename(src, dst), posix.unlink(path), posix.symlink(src, dst), posix.readlink(path). Flags: posix.O_RDONLY, posix.O_WRONLY, posix.O_RDWR, posix.O_CREAT, posix.O_TRUNC, posix.O_NONBLOCK. Prefer os for portability; use posix directly only when you need the raw C-level names in documentation or introspection. Claude Code generates low-level fd pipelines, fork/exec process managers, POSIX syscall wrappers, and fd-level I/O dispatchers.

CLAUDE.md for posix

## posix Stack
- Stdlib: import posix  (Linux/macOS; os re-exports all of posix on POSIX systems)
- Open:   fd = posix.open(path, posix.O_RDONLY)
- Read:   data = posix.read(fd, 4096)
- Write:  posix.write(fd, b"data")
- Close:  posix.close(fd)
- Fork:   pid = posix.fork()          # 0=child, >0=parent
- Exec:   posix.execv(path, args)     # replaces current process
- Stat:   result = posix.stat(path)   # .st_size .st_mode .st_mtime
- Prefer: use `os` for portable code; use `posix` when C-level names matter

posix Direct POSIX Syscall Pipeline

# app/posixutil.py — fd I/O, fork/exec, stat, working directory ops
from __future__ import annotations

import os
import platform
import signal
import stat as stat_module
from dataclasses import dataclass

_POSIX_AVAILABLE = platform.system() != "Windows"
if _POSIX_AVAILABLE:
    import posix


# ─────────────────────────────────────────────────────────────────────────────
# 1. File-descriptor level I/O
# ─────────────────────────────────────────────────────────────────────────────

def open_fd(path: str, flags: int = None, mode: int = 0o666) -> int:
    """
    Open a file at the POSIX level, returning a raw file descriptor int.
    flags defaults to O_RDONLY.

    Example:
        fd = open_fd("/etc/hostname")
        data = read_fd(fd, 256)
        close_fd(fd)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    if flags is None:
        flags = posix.O_RDONLY
    return posix.open(path, flags, mode)


def read_fd(fd: int, n: int = 4096) -> bytes:
    """
    Read up to n bytes from a file descriptor.

    Example:
        data = read_fd(fd, 8192)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    return posix.read(fd, n)


def read_fd_all(fd: int, chunk: int = 65536) -> bytes:
    """
    Read all bytes from a file descriptor until EOF.

    Example:
        fd = open_fd("/proc/cpuinfo")
        content = read_fd_all(fd)
        close_fd(fd)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    buf = bytearray()
    while True:
        chunk_data = posix.read(fd, chunk)
        if not chunk_data:
            break
        buf.extend(chunk_data)
    return bytes(buf)


def write_fd(fd: int, data: bytes) -> int:
    """
    Write bytes to a file descriptor. Returns bytes written.

    Example:
        written = write_fd(fd, b"hello\n")
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    return posix.write(fd, data)


def write_fd_all(fd: int, data: bytes) -> None:
    """
    Write all bytes to a file descriptor, retrying on short writes.

    Example:
        write_fd_all(fd, large_payload)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    offset = 0
    while offset < len(data):
        n = posix.write(fd, data[offset:])
        offset += n


def close_fd(fd: int) -> None:
    """Close a file descriptor, ignoring EBADF."""
    if not _POSIX_AVAILABLE:
        return
    try:
        posix.close(fd)
    except OSError:
        pass


def pipe_bytes(data: bytes) -> bytes:
    """
    Write data to one end of a pipe, read it back from the other.
    Demonstrates posix.pipe() + fork-based data passing.

    Example:
        result = pipe_bytes(b"hello world")
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    r_fd, w_fd = posix.pipe()
    pid = posix.fork()
    if pid == 0:
        # Child: write data and exit
        posix.close(r_fd)
        write_fd_all(w_fd, data)
        posix.close(w_fd)
        posix._exit(0)
    # Parent: read data
    posix.close(w_fd)
    result = read_fd_all(r_fd)
    posix.close(r_fd)
    posix.waitpid(pid, 0)
    return result


# ─────────────────────────────────────────────────────────────────────────────
# 2. stat / filesystem
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class StatInfo:
    path:  str
    size:  int
    mode:  int
    uid:   int
    gid:   int
    mtime: float
    inode: int
    is_dir:     bool
    is_file:    bool
    is_symlink: bool

    def mode_str(self) -> str:
        return stat_module.filemode(self.mode)

    def __str__(self) -> str:
        return (f"{self.mode_str()}  "
                f"uid={self.uid}  gid={self.gid}  "
                f"size={self.size:>10d}  "
                f"inode={self.inode}  "
                f"{self.path}")


def stat_path(path: str) -> StatInfo:
    """
    Stat a path using posix.stat(). Does not follow symlinks.

    Example:
        info = stat_path("/etc/hostname")
        print(info)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    s = posix.stat(path)
    return StatInfo(
        path=path,
        size=s.st_size,
        mode=s.st_mode,
        uid=s.st_uid,
        gid=s.st_gid,
        mtime=s.st_mtime,
        inode=s.st_ino,
        is_dir=stat_module.S_ISDIR(s.st_mode),
        is_file=stat_module.S_ISREG(s.st_mode),
        is_symlink=stat_module.S_ISLNK(posix.lstat(path).st_mode),
    )


def listdir_stat(directory: str) -> list[StatInfo]:
    """
    List a directory and stat each entry.

    Example:
        entries = listdir_stat("/tmp")
        for e in sorted(entries, key=lambda e: e.size, reverse=True)[:5]:
            print(e)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    results = []
    for name in posix.listdir(directory):
        full = os.path.join(directory, name)
        try:
            results.append(stat_path(full))
        except OSError:
            pass
    return results


# ─────────────────────────────────────────────────────────────────────────────
# 3. Fork / exec helpers
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class ProcessResult:
    pid:        int
    exit_code:  int
    signaled:   bool
    signal_num: int | None


def fork_and_run(fn, *args) -> ProcessResult:
    """
    Fork a child process, call fn(*args) in the child, and wait.
    Child exit code is fn's return value (0 if None, 1 on exception).

    Example:
        result = fork_and_run(lambda: print("hello from child"))
        print(result.exit_code)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    pid = posix.fork()
    if pid == 0:
        try:
            ret = fn(*args)
            posix._exit(0 if ret is None else int(ret))
        except Exception:
            posix._exit(1)
    _, raw_status = posix.waitpid(pid, 0)
    return ProcessResult(
        pid=pid,
        exit_code=os.waitstatus_to_exitcode(raw_status),
        signaled=os.WIFSIGNALED(raw_status),
        signal_num=os.WTERMSIG(raw_status) if os.WIFSIGNALED(raw_status) else None,
    )


def exec_replace(path: str, args: list[str], env: dict[str, str] | None = None) -> None:
    """
    Replace the current process with path/args using posix.execve().
    Never returns on success.

    Example:
        exec_replace("/bin/echo", ["echo", "hello"])
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    if env is None:
        posix.execv(path, args)
    else:
        posix.execve(path, args, env)


def spawn_command(argv: list[str], env: dict[str, str] | None = None) -> ProcessResult:
    """
    Fork a child, exec argv[0] with argv, wait for completion.

    Example:
        result = spawn_command(["ls", "-la", "/tmp"])
        print(result.exit_code)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    pid = posix.fork()
    if pid == 0:
        try:
            if env is None:
                posix.execv(argv[0], argv)
            else:
                posix.execve(argv[0], argv, env)
        except OSError:
            posix._exit(127)
    _, raw_status = posix.waitpid(pid, 0)
    return ProcessResult(
        pid=pid,
        exit_code=os.waitstatus_to_exitcode(raw_status),
        signaled=os.WIFSIGNALED(raw_status),
        signal_num=os.WTERMSIG(raw_status) if os.WIFSIGNALED(raw_status) else None,
    )


# ─────────────────────────────────────────────────────────────────────────────
# 4. Process identity / environment
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class ProcessIdentity:
    pid:   int
    ppid:  int
    uid:   int
    gid:   int
    euid:  int
    egid:  int
    cwd:   str
    login: str

    def __str__(self) -> str:
        return (f"pid={self.pid}  ppid={self.ppid}  "
                f"uid={self.uid}  gid={self.gid}  "
                f"euid={self.euid}  egid={self.egid}  "
                f"login={self.login!r}  cwd={self.cwd!r}")


def process_identity() -> ProcessIdentity:
    """
    Return the current process's POSIX identity.

    Example:
        ident = process_identity()
        print(ident)
    """
    if not _POSIX_AVAILABLE:
        raise OSError("posix not available on Windows")
    try:
        login = posix.getlogin()
    except OSError:
        login = ""
    return ProcessIdentity(
        pid=posix.getpid(),
        ppid=posix.getppid(),
        uid=posix.getuid(),
        gid=posix.getgid(),
        euid=posix.geteuid(),
        egid=posix.getegid(),
        cwd=posix.getcwd(),
        login=login,
    )


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== posix demo ===")

    if not _POSIX_AVAILABLE:
        print("  posix not available on Windows — skipping")
        raise SystemExit(0)

    # ── identity ───────────────────────────────────────────────────────────────
    print("\n--- process_identity ---")
    ident = process_identity()
    print(f"  {ident}")

    # ── fd I/O ─────────────────────────────────────────────────────────────────
    print("\n--- fd read /etc/hostname ---")
    fd = open_fd("/etc/hostname")
    hostname = read_fd_all(fd).decode().strip()
    close_fd(fd)
    print(f"  hostname: {hostname!r}")

    # ── stat ───────────────────────────────────────────────────────────────────
    print("\n--- stat_path ---")
    for p in ["/etc/hostname", "/tmp", "/bin/sh"]:
        try:
            info = stat_path(p)
            print(f"  {info}")
        except OSError as e:
            print(f"  {p}: {e}")

    # ── listdir_stat ───────────────────────────────────────────────────────────
    print("\n--- listdir_stat /etc (first 5 by size) ---")
    entries = listdir_stat("/etc")
    for e in sorted(entries, key=lambda e: e.size, reverse=True)[:5]:
        print(f"  {e}")

    # ── pipe_bytes ─────────────────────────────────────────────────────────────
    print("\n--- pipe_bytes ---")
    payload = b"hello from parent via posix pipe"
    received = pipe_bytes(payload)
    print(f"  sent:     {payload!r}")
    print(f"  received: {received!r}")
    print(f"  match: {payload == received}")

    # ── spawn_command ──────────────────────────────────────────────────────────
    print("\n--- spawn_command ['uname', '-s'] ---")
    result = spawn_command(["/usr/bin/uname", "-s"])
    print(f"  exit_code={result.exit_code}  signaled={result.signaled}")

    print("\n=== done ===")

For the os alternative — os is the portable stdlib interface that re-exports everything in posix plus Windows equivalents — prefer os in all production code since import os works on every platform and provides the same functions (os.open, os.read, os.write, os.fork, os.execv, os.stat) with identical signatures; use posix directly only when documenting the POSIX C layer, writing introspection tooling (dir(posix) to enumerate available syscalls), or when the explicit POSIX namespacing aids clarity in systems-level documentation. For the subprocess alternative — subprocess.run([...]) and subprocess.Popen wrap fork/exec/waitpid into a higher-level API with stdio capture, timeout enforcement, and communicate() — use subprocess when you need captured output, shell pipelines, or cross-platform process spawning; use posix.fork() + posix.execv() directly when you need fine-grained control over open file descriptors, supplementary groups, process sessions, or pre-exec hooks that subprocess does not expose. The Claude Skills 360 bundle includes posix skill sets covering open_fd()/read_fd()/read_fd_all()/write_fd_all()/close_fd()/pipe_bytes() fd-level I/O, StatInfo with stat_path()/listdir_stat() filesystem inspection, ProcessResult with fork_and_run()/exec_replace()/spawn_command() process management, and ProcessIdentity with process_identity() POSIX identity reporting. Start with the free tier to try POSIX syscall patterns and posix 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