Claude Code for cmd: Python Interactive Command Interpreter — Claude Skills 360 Blog
Blog / AI / Claude Code for cmd: Python Interactive Command Interpreter
AI

Claude Code for cmd: Python Interactive Command Interpreter

Published: September 29, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s cmd module provides a framework for building line-oriented interactive command interpreters. import cmd. Cmd: subclass cmd.Cmd; define do_NAME(self, arg) methods for commands; help_NAME docstrings or methods for help. cmdloop: self.cmdloop(intro="Welcome") — starts the REPL; reads lines, splits on first space, dispatches to do_NAME(arg); exits on EOF or do_NAME returning True. onecmd: self.onecmd("cmd arg1 arg2") — dispatch one line programmatically. default: def default(self, line) — called for unknown commands (default prints *** Unknown syntax). emptyline: def emptyline(self) — called on empty input (default re-runs last command; override to do nothing). precmd/postcmd: hooks before/after every command. completedefault: tab completion fallback; complete_NAME(text, line, begidx, endidx) for per-command completion. prompt: self.prompt = "myapp> ". identchars: characters valid in command names. ruler: "=" drawn in help headers. doc_header/undoc_header. self.stop = True exits cmdloop. help command built-in: prints do_NAME.__doc__. subclasses can chain with cmd.Cmd.__init__(self, stdin=..., stdout=...). Claude Code generates multi-command admin shells, debug REPLs, interactive data explorers, and scriptable CLI interpreters.

CLAUDE.md for cmd

## cmd Stack
- Stdlib: import cmd, shlex
- Class:  class MyShell(cmd.Cmd): prompt = "app> "
- Command: def do_list(self, arg): ...  # "list" command
- Help:    def do_list(self, arg): """List all items."""
- Complete: def complete_list(self, text, line, begidx, endidx): return matches
- Exit:    def do_quit(self, arg): return True   # True stops cmdloop
- Run:     MyShell().cmdloop()

cmd Shell Pipeline

# app/cmdshell.py — base shell, history, argparse commands, subcommands, testing
from __future__ import annotations

import cmd
import shlex
import sys
from dataclasses import dataclass, field
from io import StringIO
from typing import Any


# ─────────────────────────────────────────────────────────────────────────────
# 1. Base shell with common features
# ─────────────────────────────────────────────────────────────────────────────

class BaseShell(cmd.Cmd):
    """
    cmd.Cmd subclass with sensible defaults:
    - emptyline() is a no-op (not re-run last command)
    - EOF exits cleanly
    - 'quit' / 'exit' / 'q' all exit
    - error() helper for consistent error output
    - history stored in self._history

    Example:
        class MyApp(BaseShell):
            prompt = "myapp> "
            def do_greet(self, arg):
                """Greet someone. Usage: greet <name>"""
                print(f"Hello, {arg or 'world'}!")
        MyApp().cmdloop()
    """

    prompt    = "shell> "
    intro     = None
    doc_header   = "Commands (type help <command>):"
    undoc_header = "Undocumented commands:"
    ruler        = "-"

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._history: list[str] = []

    def emptyline(self) -> None:
        """Do nothing on empty line (override cmd.Cmd default of re-running last command)."""

    def default(self, line: str) -> bool | None:
        self.error(f"Unknown command: {line.split()[0]!r}  (type 'help' for commands)")
        return None

    def error(self, msg: str) -> None:
        print(f"Error: {msg}", file=self.stdout)

    def precmd(self, line: str) -> str:
        if line.strip():
            self._history.append(line.strip())
        return line

    def do_quit(self, arg: str) -> bool:
        """Exit the shell."""
        return True

    do_exit = do_quit
    do_q    = do_quit

    def do_EOF(self, arg: str) -> bool:
        """Exit on Ctrl-D."""
        print()
        return True

    def do_history(self, arg: str) -> None:
        """Show command history."""
        if not self._history:
            print("  (no history)")
        for i, cmd_line in enumerate(self._history, 1):
            print(f"  {i:3d}  {cmd_line}")

    def do_clear(self, arg: str) -> None:
        """Clear the terminal screen."""
        import os
        os.system("cls" if sys.platform == "win32" else "clear")


# ─────────────────────────────────────────────────────────────────────────────
# 2. Argument-parsing helper
# ─────────────────────────────────────────────────────────────────────────────

def parse_args(arg: str) -> list[str]:
    """
    Split a readline arg string into tokens using POSIX shell rules.
    Handles quoted strings: parse_args('one "two three" four') → ['one', 'two three', 'four']

    Example:
        def do_add(self, arg):
            tokens = parse_args(arg)
            if len(tokens) < 2: return self.error("Usage: add <name> <value>")
            name, value = tokens[0], tokens[1]
    """
    try:
        return shlex.split(arg)
    except ValueError:
        return arg.split()


# ─────────────────────────────────────────────────────────────────────────────
# 3. Key-value store shell (concrete example)
# ─────────────────────────────────────────────────────────────────────────────

class KVShell(BaseShell):
    """
    Interactive shell for a simple in-memory key-value store.
    Demonstrates do_*/complete_*/help_ patterns.

    Example:
        KVShell().cmdloop("Welcome to KV shell. Type 'help' for commands.")
    """

    prompt = "kv> "

    def __init__(self) -> None:
        super().__init__()
        self._store: dict[str, str] = {}

    # ── commands ──────────────────────────────────────────────────────────────

    def do_set(self, arg: str) -> None:
        """Set a key-value pair.  Usage: set <key> <value>"""
        tokens = parse_args(arg)
        if len(tokens) < 2:
            return self.error("Usage: set <key> <value>")
        key, value = tokens[0], " ".join(tokens[1:])
        self._store[key] = value
        print(f"  {key} = {value!r}")

    def do_get(self, arg: str) -> None:
        """Get the value for a key.  Usage: get <key>"""
        key = arg.strip()
        if not key:
            return self.error("Usage: get <key>")
        val = self._store.get(key)
        if val is None:
            print(f"  (not found: {key!r})")
        else:
            print(f"  {key} = {val!r}")

    def do_del(self, arg: str) -> None:
        """Delete a key.  Usage: del <key>"""
        key = arg.strip()
        if key in self._store:
            del self._store[key]
            print(f"  deleted {key!r}")
        else:
            self.error(f"Not found: {key!r}")

    def do_list(self, arg: str) -> None:
        """List all keys (optionally filter by prefix).  Usage: list [prefix]"""
        prefix = arg.strip()
        items = [(k, v) for k, v in sorted(self._store.items())
                 if k.startswith(prefix)]
        if not items:
            print("  (empty)")
        for k, v in items:
            print(f"  {k:20s} = {v!r}")

    def do_import(self, arg: str) -> None:
        """Load key=value pairs from a file.  Usage: import <path>"""
        path = arg.strip()
        if not path:
            return self.error("Usage: import <path>")
        try:
            with open(path) as f:
                for line in f:
                    line = line.strip()
                    if "=" in line and not line.startswith("#"):
                        k, _, v = line.partition("=")
                        self._store[k.strip()] = v.strip()
            print(f"  imported from {path!r}")
        except OSError as e:
            self.error(str(e))

    def do_export(self, arg: str) -> None:
        """Write all key=value pairs to a file.  Usage: export <path>"""
        path = arg.strip()
        if not path:
            return self.error("Usage: export <path>")
        with open(path, "w") as f:
            for k, v in sorted(self._store.items()):
                f.write(f"{k}={v}\n")
        print(f"  exported {len(self._store)} keys to {path!r}")

    # ── completion ────────────────────────────────────────────────────────────

    def complete_get(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:
        return [k for k in self._store if k.startswith(text)]

    def complete_del(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:
        return [k for k in self._store if k.startswith(text)]

    def complete_set(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:
        tokens = parse_args(line)
        # Only complete the key (first token after command)
        if len(tokens) <= 1 or (len(tokens) == 2 and not line.endswith(" ")):
            return [k for k in self._store if k.startswith(text)]
        return []


# ─────────────────────────────────────────────────────────────────────────────
# 4. Scriptable command runner (non-interactive)
# ─────────────────────────────────────────────────────────────────────────────

def run_script(
    shell_cls: type,
    commands: list[str],
    **shell_kwargs,
) -> str:
    """
    Run a list of commands through a cmd.Cmd subclass non-interactively.
    Returns all output as a string.

    Example:
        output = run_script(KVShell, [
            "set name Alice",
            "set score 99",
            "list",
            "get name",
        ])
        print(output)
    """
    stdin  = StringIO("\n".join(commands) + "\nEOF\n")
    stdout = StringIO()
    shell = shell_cls(stdin=stdin, stdout=stdout, **shell_kwargs)
    shell.use_rawinput = False   # use stdin.readline() instead of input()
    shell.cmdloop()
    return stdout.getvalue()


# ─────────────────────────────────────────────────────────────────────────────
# 5. Subcommand dispatcher mixin
# ─────────────────────────────────────────────────────────────────────────────

class SubcommandMixin:
    """
    Mixin to add 'cmd subcommand args' dispatch inside a do_cmd method.
    Subclass and call dispatch_subcommand(name, arg, subs) from a do_* method.

    Example:
        class MyShell(SubcommandMixin, BaseShell):
            def do_user(self, arg):
                self.dispatch_subcommand("user", arg, {
                    "add":    self._user_add,
                    "remove": self._user_remove,
                    "list":   self._user_list,
                })
    """

    def dispatch_subcommand(
        self,
        cmd_name: str,
        arg: str,
        subs: dict[str, Any],
    ) -> None:
        tokens = parse_args(arg)
        if not tokens:
            print(f"  Subcommands: {', '.join(sorted(subs))}")
            return
        sub = tokens[0]
        rest = " ".join(tokens[1:])
        fn = subs.get(sub)
        if fn is None:
            print(f"  Unknown subcommand: {sub!r}", file=getattr(self, "stdout", sys.stdout))
            print(f"  Available: {', '.join(sorted(subs))}", file=getattr(self, "stdout", sys.stdout))
        else:
            fn(rest)


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

if __name__ == "__main__":
    print("=== cmd demo (non-interactive) ===")

    # ── run KVShell via script ─────────────────────────────────────────────────
    print("\n--- KVShell scripted run ---")
    output = run_script(KVShell, [
        "set name Alice",
        "set score 99",
        "set tag admin",
        "list",
        "get name",
        "del tag",
        "list",
        "history",
    ])
    for line in output.splitlines():
        print(" ", line)

    # ── completion smoke test ──────────────────────────────────────────────────
    print("\n--- completion ---")
    shell = KVShell()
    # Pre-populate store
    shell._store = {"alpha": "1", "beta": "2", "gamma": "3"}
    matches = shell.complete_get("al", "get al", 4, 6)
    print(f"  complete_get('al') → {matches}")

    # ── parse_args ────────────────────────────────────────────────────────────
    print("\n--- parse_args ---")
    cases = [
        'simple arg',
        '"quoted value" arg2',
        'key "value with spaces"',
    ]
    for c in cases:
        print(f"  {c!r}{parse_args(c)}")

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

For the readline alternative — readline (stdlib) provides the lower-level line-editing and Tab-completion primitives that cmd.Cmd uses internally; you get direct control over set_completer, parse_and_bind, and history file management — use readline directly when building a prompt loop with input() that needs custom history or completion but doesn’t fit the do_* method dispatch model; use cmd.Cmd when your CLI has a structured set of named commands with built-in help wiring and per-command Tab completion via complete_* methods. For the click / typer alternative — click (PyPI) and typer (PyPI) build single-invocation CLI tools (git-style app command --flag) rather than interactive REPLs; they provide argument parsing, type checking, --help generation, and shell completion scripts automatically — use click/typer for non-interactive command-line tools that are invoked once per call; use cmd.Cmd for interactive multi-command shells that users run in a loop (db> set key val, db> list, db> quit). The Claude Skills 360 bundle includes cmd skill sets covering BaseShell with history/error/quit/EOF built-ins, KVShell concrete example with set/get/del/list/import/export commands and complete_* hooks, parse_args() shlex helper, run_script() non-interactive test runner, and SubcommandMixin for cmd sub args dispatch patterns. Start with the free tier to try interactive shell patterns and cmd 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