On this page
  1. code
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Feeding Lines Programmatically to InteractiveConsole
  7. 2. Launching a Debug Shell on Demand
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

code

Prev: cmd | Up: stdlib_module | Next: codecs
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — code
Tags: #public #python3 #stdlib


Import

import code

Overview

Utilities for embedding an interactive Python read-eval-print loop (REPL) inside an application (InteractiveInterpreter, InteractiveConsole, interact(), compile_command()). Use code when you want to drop a user into a live Python shell pre-populated with your app's runtime objects, or build a custom notebook/sandbox REPL.

Quick Start

import code

# Drop into an interactive Python prompt with pre-bound locals
# (In scripts, call code.interact(local={"app_version": "1.0"}))
compiled = code.compile_command("x = 2 + 2")
assert compiled is not None

# Incomplete multi-line statement returns None (prompt for more input)
assert code.compile_command("if True:") is None

Implementation Walkthrough

1. Feeding Lines Programmatically to InteractiveConsole

InteractiveConsole.push(line) buffers multi-line blocks and returns True when more input is needed (... ) or False once a complete statement has executed:

import code
import contextlib
import io

ns: dict[str, object] = {}
console = code.InteractiveConsole(locals=ns)
buf = io.StringIO()

with contextlib.redirect_stdout(buf):
    assert console.push("def double(n):") is True
    assert console.push("    return n * 2") is True
    assert console.push("") is False
    assert console.push("print(double(21))") is False

assert buf.getvalue().strip() == "42"

2. Launching a Debug Shell on Demand

code.interact() starts a live REPL with your current variables without importing pdb:

import code

def inspect_state(state: dict[str, object]) -> None:
    code.interact(
        banner="App debug console (Ctrl-D to resume)",
        local=state,
        exitmsg="Resuming execution.",
    )

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes