exec - return value of expression

Christoph Groth cgroth at gmx.net
Fri Feb 13 18:27:27 EST 2004


Hello,

If a statement being executed with `exec' (the statement was
compile()'d with "single" as kind) evaluates to something else than
`None', the representation of that object is printed to sys.stdout.

Now I would like to execute arbitrary python statements in a
sub-interpreter (like code.InteractiveInterpreter) but instead of
printing the returned objects, I would like to get them, so I can
decide how to print them.

It seems that the `eval' builtin function is not what I want, as
>>> c = compile('x=1', '<input>', 'eval')
yields an error.  Apparently `eval' is only suited for executing
expressions and not arbitrary code.

What I need this for is the following:

I'm currently writing a small computer algebra system in python.  In
order to have a nice way of working interactively with the system I've
created a python application which behaves like a python interpreter
(it uses code.InteractiveInterpreter) and which is used as a plugin
for the texmacs editor.  texmacs, which is able to to typeset formula
in TeX-manner, acts as a frontend to the interpreter.

Currently, if the user wants to print some formula, say, he has to
execute a function called `tex' which packages the TeX-representation
of the formula in a way understood by texmacs, like this:

>>> f = create_some_formula()
>>> tex(f)   # Prettyprint the formula

But typing tex( ) all the time is a bit annoying, I would like that
the following works inside my texmacs-plugin.

>>> f = create_some_formula()
>>> f  # Prettyprint the formula

One solution would be to change the __repr__-Methods of the objects
which are to be prettyprinted.  This should work, but I would like to
prettyprint some builtin objects too, like a list of formulas for
example.  And I don't know how to change the __repr__ of builtin
lists.

Any hints on how to solve this Problem in an elegant way are greatly
appreciated.

Christoph
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 238 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040214/6a23da45/attachment.sig>


More information about the Python-list mailing list