how to distinguish a python expression from a statement?
James_Althoff at i2.com
James_Althoff at i2.com
Tue Sep 4 13:13:03 EDT 2001
Thanks for your suggestion, Fredrik.
I must be doing something wrong, though, because I don't seem to be getting
the expected behaviour. The magic "_" variable works when I type directly
into the Python interpreter (interactive mode). But when I run your
example code using either Python or Jython, "_" is not defined (as part of
the exec statement).
Python 2.2a1 (#21, Jul 18 2001, 04:25:46) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> mysource = '3+4'
>>> dict = {}
>>> code = compile(mysource,"<stdin>","single")
>>> exec code in dict
7
>>> result = dict.get("_")
>>> if result is not None:
... print result
...
>>> print result
None
>>>
>>>
>>> 3+5
8
>>> _
8
>>>
Do I need to do something special to enable the magic "_" to be included in
an exec statement?
Thanks,
Jim
Fredrik Lundh wrote:
>sure:
>James_Althoff at i2.com wrote:
>> 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?
>
>
> dict = {}
> code = compile(mysource, "<stdin>", "single")
> exec code in dict
> result = dict.get("_")
> if result is not None:
> print result
>
>(use dict.has_key("_") to check if it really was an expression)
>
>> I am trying to mimick the Python interpreter in a GUI.
>
>the "code" module contains a framework for this; just instantiate
>an InteractiveConsole, and use the "push" method to add lines as
>they arrive from the GUI.
>
></F>
<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
--
http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list