There is no way to obtain the value of the last Python expression
evaluated by exec. Interactive mode does this by using a special
start symbol of the grammar, which takes either an expression or a
single statement (which may be compound, e.g. 'if', but not multiple
simple statements). Then the generated code contains "PRINT_EXPR"
instructions which print the value on stdout (unless it is None).
A trick I have used in other applications that want to behave similar
to the interpreter is the following: whenever the user submits some
code, first try if it can be parsed as an expression. If so, evaluate
the expression and print its value. If the parse fails, hide the
errors (i.e. just catch the exception) and reparse it as "exec input"
-- this will correctly parse it if it was a statement, or give the
errors when there was a syntax error.
--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>