On this page
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
- Not a security sandbox: Code executed via
InteractiveInterpreterorInteractiveConsoleruns with full Python interpreter privileges. SyntaxErrorand runtime exceptions are printed, not raised:runsource()andpush()catch exceptions and print formatted tracebacks tosys.stderr; overrideshowsyntaxerror()/showtraceback()to capture them.- Pass
exitmsg=""if you want silent exit: Otherwiseinteract()printsnow exiting InteractiveConsole...when the user pressesCtrl-D.
Common Functions
- code.compile_command() —
compile_command(source, filename='<input>', symbol='single', flags=0)— Compile a command and determine whether it is incomplete. - code.interact() —
interact(banner=None, readfunc=None, local=None, exitmsg=None, local_exit=False)— Closely emulate the interactive Python interpreter.
Classes & Objects
- code.InteractiveConsole — Closely emulate the behavior of the interactive Python interpreter. (Methods:
.interact(),.push(),.raw_input(),.resetbuffer(),.runcode(),.runsource()) - code.InteractiveInterpreter — Base class for InteractiveConsole. (Methods:
.runcode(),.runsource(),.showsyntaxerror(),.showtraceback(),.write())
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/cmd
- tuts/python3/stdlib_module/code/compile_command
- tuts/python3/stdlib_module/code/interact
- tuts/python3/stdlib_module/code/InteractiveConsole
- tuts/python3/stdlib_module/code/InteractiveInterpreter
- tuts/python3/stdlib_module/codecs
- tuts/python3/stdlib_module/codeop
- tuts/python3/stdlib_module/rlcompleter
- tuts/python3/stdlib_module/stdlib_module
Related notes
- tuts/python3/stdlib_module/cmd Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/code/compile_command Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/code/interact Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/code/InteractiveConsole Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/code/InteractiveInterpreter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/codeop links to this page; shared tags: #stdlib