how to distinguish a python expression from a statement?
James_Althoff at i2.com
James_Althoff at i2.com
Tue Sep 4 14:05:05 EDT 2001
Thanks for your response, Peter. Actually, that is the approach I had been
experimenting with. But I was worried that catching the SyntaxError in
eval as a way of "discovering" a statement (as opposed to an expression)
could somehow mask an actual syntax error in an expression. But in
thinking about it more, I guess there is no problem with that since the
exec works on both expressions and statements. And so a bad expression
passed to exec will result in exec throwing a SyntaxError a second time,
which I suppose is fine for my purposes.
I will also look into the code module more. But I'm not really doing an
exact replica of the interactive Python interpreter. I'm doing a GUI-based
variant that is more like a Smalltalk workspace -- but with the twist that
the output always goes into a separate (from the input) text pane. Maybe
the code module will still help.
Thanks again,
Jim
Peter Hansen wrote:
=====================
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
--
http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list