The code Module

The code module provides a number of functions that can be used to emulate the behavior of the standard interpreter’s interactive mode.

The compile_command behaves like the built-in compile function, but does some additional tests to make sure you pass it a complete Python statement.

In Example 2-47, we’re compiling a program line by line, executing the resulting code objects as soon as we manage to compile. The program looks like this:

a = (
  1,
  2,
  3
)
print a

Note that the tuple assignment cannot be properly compiled until we’ve reached the second parenthesis.

Example 2-47. Using the code Module to Compile Statements

File: code-example-1.py

import code
import string

# 
SCRIPT = [
    "a = (",
    "  1,",
    "  2,",
    "  3 ",
    ")",
    "print a"
]

script = ""

for line in SCRIPT:
    script = script + line + "\n"
    co = code.compile_command(script, "<stdin>", "exec")
    if co:
        # got a complete statement.  execute it!
        print "-"*40
        print script,
        print "-"*40
        exec co
        script = ""

----------------------------------------
a = (
  1,
  2,
  3 
)
----------------------------------------
----------------------------------------
print a
----------------------------------------
(1, 2, 3)

The InteractiveConsole class implements an interactive console, much like the one you get when you fire up the Python interpreter in interactive mode.

The console can be either active (it calls a function to get the next line) or passive (you call the push method when you have new data). The default is to use the built-in raw_input ...

Get Python Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.