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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access