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.