how to distinguish a python expression from a statement?
Peter Hansen
peter at engcorp.com
Fri Aug 31 23:59:41 EDT 2001
James_Althoff at i2.com wrote:
>
> 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?
This might give you some ideas:
>>> def f(str):
... try:
... result = eval(str)
... except SyntaxError:
... exec str
... result = None
... return result
...
>>> f('5*5')
25
>>> f('print "hi"')
hi
>>>
On the other hand, as some kind soul showed me when I asked
a related question a while back, there are also the modules
'codeop' and 'code', which probably already have want you
need...
--
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com
More information about the Python-list
mailing list