how to distinguish a python expression from a statement?

James_Althoff at i2.com James_Althoff at i2.com
Fri Aug 31 19:45:51 EDT 2001


I have a string, inputText, which is a fragment of python code plucked from
a text control in a GUI.  If the value of inputText  is an expression then
I will do "result = eval(inputText,globalsDict,localsDict)" and show result
in the GUI.  If it is a statement, I will do "exec inputText in
globalsDict, localsDict" (and I know about redirecting sys.stdout while
doing either).

I have all of this working except that I don't know how to distinguish
between expressions and statements (without making the end user push one of
two different buttons in order to tell me -- yuk).  I am using Jython and
so the parser module is not available (so I can't use parser.isexpr).

Is there any means to accomplish this what-I-had-thought-would-be-routine
task short of writing a Python parser?

The big picture:
o get a string
o "exec/eval" it
o if the string represents an expression, display the result -- since
statements have no results in Python this only makes sense for expressions
i.e., I am trying to mimick the Python interpreter in a GUI.

(Someone, please rescue me :-)

Thanks,

Jim





More information about the Python-list mailing list