Claude Code for uu: Python UUencoding Utilities — Claude Skills 360 Blog
Blog / AI / Claude Code for uu: Python UUencoding Utilities
AI

Claude Code for uu: Python UUencoding Utilities

Published: January 8, 2029
Read time: 5 min read
By: Claude Skills 360

Python’s uu module encodes and decodes the uuencoding format — a legacy ASCII encoding used historically for binary attachments in USENET posts and early email. import uu. Encode: uu.encode(in_file, out_file, name="file.bin", mode=0o644, backtick=False) — reads binary from in_file, writes uuencoded ASCII to out_file; the header line is begin 644 file.bin and the trailer is end. Decode: uu.decode(in_file, out_file=None, mode=None, quiet=False) — reads uuencoded text, writes binary; if out_file is omitted the filename from the begin header is used. Error: uu.Error raised for malformed input. Note: deprecated since Python 3.11; base64 is the modern replacement for binary-to-text encoding. The encoding maps each 3 bytes to 4 printable ASCII characters (space = 0, ! = 1, … ~ = 63); a space may be replaced by a backtick for email safety. Claude Code generates legacy archive readers, email attachment decoders, format converters, and USENET compatibility tools.

CLAUDE.md for uu

## uu Stack
- Stdlib: import uu, io    (deprecated Python 3.11+)
- Encode: uu.encode(io.BytesIO(data), out, name="file", mode=0o644)
- Decode: uu.decode(text_io, binary_out)
- Files:  uu.encode(open("in.bin","rb"), open("out.uu","w"))
-         uu.decode(open("data.uu","r"), out=None)  # uses filename from header
- Error:  uu.Error for malformed input
- Note:   use base64 for new code; uu for legacy USENET/email compatibility

uu Encoding Pipeline

# app/uuutil.py — encode, decode, roundtrip, file tools, header parser
from __future__ import annotations

import io
import os
import uu
from dataclasses import dataclass
from pathlib import Path


# ─────────────────────────────────────────────────────────────────────────────
# 1. In-memory encode / decode
# ─────────────────────────────────────────────────────────────────────────────

def encode_bytes(
    data: bytes,
    name: str = "data.bin",
    mode: int = 0o644,
    backtick: bool = False,
) -> str:
    """
    Encode bytes to a uuencoded string.

    Example:
        text = encode_bytes(b"Hello, uuencode!", name="hello.txt")
        print(text[:30])   # "begin 644 hello.txt\\n..."
    """
    in_buf = io.BytesIO(data)
    out_buf = io.StringIO()
    uu.encode(in_buf, out_buf, name=name, mode=mode, backtick=backtick)
    return out_buf.getvalue()


def decode_string(uutext: str) -> tuple[str, bytes]:
    """
    Decode a uuencoded string and return (original_name, bytes).

    Example:
        name, data = decode_string(encoded_text)
        print(name, len(data))
    """
    in_buf = io.StringIO(uutext)
    out_buf = io.BytesIO()

    # We need to know the filename from the header before decoding
    # Peek at the first line
    lines = uutext.splitlines()
    header_name = "output"
    if lines and lines[0].startswith("begin"):
        parts = lines[0].split()
        if len(parts) >= 3:
            header_name = parts[2]

    uu.decode(in_buf, out_buf)
    return header_name, out_buf.getvalue()


def roundtrip_check(data: bytes, name: str = "test.bin") -> bool:
    """
    Encode then decode data and verify it matches the original.

    Example:
        assert roundtrip_check(b"binary data \\x00\\x01\\x02\\xff")
    """
    encoded = encode_bytes(data, name=name)
    _, decoded = decode_string(encoded)
    return decoded == data


# ─────────────────────────────────────────────────────────────────────────────
# 2. File-level encode / decode
# ─────────────────────────────────────────────────────────────────────────────

def encode_file(src: "str | Path", dest: "str | Path | None" = None, **kwargs) -> Path:
    """
    Encode a binary file to a .uu file.
    If dest is omitted, appends '.uu' to the source path.

    Example:
        out = encode_file("logo.png")
        print(out)   # logo.png.uu
    """
    src = Path(src)
    dest = Path(dest) if dest else src.with_suffix(src.suffix + ".uu")
    with src.open("rb") as fin, dest.open("w") as fout:
        uu.encode(fin, fout, name=src.name, **kwargs)
    return dest


def decode_file(src: "str | Path", dest_dir: "str | Path | None" = None) -> Path:
    """
    Decode a .uu file to its original binary.
    If dest_dir is omitted, decodes into the same directory as src.

    Example:
        out = decode_file("logo.png.uu")
        print(out)   # logo.png
    """
    src = Path(src)
    dir_path = Path(dest_dir) if dest_dir else src.parent

    # Peek at header to get output filename
    with src.open("r") as f:
        first_line = f.readline().strip()
    parts = first_line.split()
    out_name = parts[2] if len(parts) >= 3 else src.stem

    out_path = dir_path / out_name
    with src.open("r") as fin, out_path.open("wb") as fout:
        uu.decode(fin, fout)
    return out_path


# ─────────────────────────────────────────────────────────────────────────────
# 3. Header inspection
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class UUHeader:
    """Information extracted from a uuencoded file header."""
    mode:     int
    mode_str: str   # octal, e.g. "644"
    name:     str
    lines:    int   # number of encoded data lines


def inspect_uu(uutext: str) -> "UUHeader | None":
    """
    Parse the header and count data lines of a uuencoded string.
    Returns None if no valid header is found.

    Example:
        hdr = inspect_uu(encoded_text)
        if hdr:
            print(hdr.name, hdr.mode_str, hdr.lines)
    """
    lines = uutext.splitlines()
    if not lines or not lines[0].startswith("begin"):
        return None
    parts = lines[0].split(maxsplit=2)
    if len(parts) < 3:
        return None
    mode_str = parts[1]
    name = parts[2]
    try:
        mode = int(mode_str, 8)
    except ValueError:
        mode = 0

    # Count data lines (not header, not empty, not "end")
    data_lines = sum(
        1 for line in lines[1:]
        if line and line != "end" and not line.startswith("begin")
    )
    return UUHeader(mode=mode, mode_str=mode_str, name=name, lines=data_lines)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Batch encode directory
# ─────────────────────────────────────────────────────────────────────────────

def encode_directory(
    src_dir: "str | Path",
    dest_dir: "str | Path | None" = None,
    pattern: str = "*",
    skip_existing: bool = True,
) -> list[Path]:
    """
    Encode all matching files in a directory to .uu files.

    Example:
        encoded = encode_directory("/opt/archive/bin", pattern="*.so")
        print(f"Encoded {len(encoded)} files")
    """
    src_dir = Path(src_dir)
    out_dir = Path(dest_dir) if dest_dir else src_dir
    out_dir.mkdir(parents=True, exist_ok=True)

    written: list[Path] = []
    for src in sorted(src_dir.glob(pattern)):
        if not src.is_file():
            continue
        dest = out_dir / (src.name + ".uu")
        if skip_existing and dest.exists():
            written.append(dest)
            continue
        out = encode_file(src, dest)
        written.append(out)
    return written


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

if __name__ == "__main__":
    import tempfile

    print("=== uu demo ===")

    # ── encode_bytes / decode_string ──────────────────────────────────────────
    print("\n--- encode_bytes / decode_string ---")
    data = b"Hello, uu world!\x00\x01\x02\xff\xfe"
    encoded = encode_bytes(data, name="hello.bin", mode=0o755)
    print(f"  encoded ({len(encoded)} chars):")
    for line in encoded.splitlines():
        print(f"    {line}")

    name, decoded = decode_string(encoded)
    print(f"  decoded name: {name!r}  data: {decoded!r}")
    print(f"  roundtrip ok: {roundtrip_check(data)}")

    # ── inspect_uu ────────────────────────────────────────────────────────────
    print("\n--- inspect_uu ---")
    hdr = inspect_uu(encoded)
    if hdr:
        print(f"  name={hdr.name!r}  mode={hdr.mode_str}  lines={hdr.lines}")

    # ── larger binary roundtrip ───────────────────────────────────────────────
    print("\n--- roundtrip_check (binary data) ---")
    for desc, payload in [
        ("zeros",    bytes(100)),
        ("255s",     bytes([255] * 100)),
        ("random",   bytes(range(256))),
    ]:
        ok = roundtrip_check(payload, name=f"{desc}.bin")
        print(f"  {desc:8s}: {'OK' if ok else 'FAIL'}")

    # ── encode_file / decode_file ─────────────────────────────────────────────
    print("\n--- encode_file / decode_file ---")
    with tempfile.TemporaryDirectory() as tmpdir:
        src = Path(tmpdir) / "test.png"
        src.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 50 + b"\x01" * 50)

        uu_path = encode_file(src)
        print(f"  encoded: {uu_path.name}  size={uu_path.stat().st_size}B")

        out_path = decode_file(uu_path, dest_dir=tmpdir + "/decoded")
        print(f"  decoded: {out_path.name}  size={out_path.stat().st_size}B")
        print(f"  match:   {out_path.read_bytes() == src.read_bytes()}")

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

For the base64 stdlib alternative — base64.b64encode(data) / base64.b64decode(s) perform Base64 encoding, which is the dominant binary-to-text format used in HTTP, JWT, email MIME parts, and data URIs; it is more compact than uuencoding (~33% overhead vs ~35%) and universally supported — always use base64 for new code; use uu only when interoperating with legacy USENET archives or old email systems that specifically deliver uuencoded attachments. For the binascii stdlib alternative — binascii.b2a_uu(data) and binascii.a2b_uu(line) expose the per-line uu codec directly without the file-wrapping and header/trailer that uu.encode/uu.decode add — use binascii.b2a_uu when you need raw per-line control of the uuencoding step; use uu.encode/uu.decode for full archive-format handling with begin/end headers. The Claude Skills 360 bundle includes uu skill sets covering encode_bytes()/decode_string()/roundtrip_check() in-memory helpers, encode_file()/decode_file() file utilities, UUHeader/inspect_uu() header inspector, and encode_directory() batch encoder. Start with the free tier to try uuencoding patterns and uu 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