[IronPython] Newbie: convert string to python expression??

Michael Foord fuzzyman at voidspace.org.uk
Tue Dec 16 16:28:36 CET 2008


Oh - and Windows Forms has a Keys enumeration so that you don't have to 
rely on the underlying value of the event key property.

from System.Windows.Forms import Keys

if e.Key == Keys.Enter:

(or something like that - check out the MSDN documentation for the 
enumeration.)

Michael Foord


Michael Foord wrote:
>
> context = {}
>
> def inputBox_KeyDown(s, e):
>    root.message.Text = ''
>    key = e.Key.value__
>    result = root.inputBox.Text
>    if key == 3: #If 'Enter' key is pressed
>     try:
>          try:
>            root.message.Text = eval(result)
>          except SyntaxError:
>            exec result in context
>       except Exception, e:
>         print 'Unhandled exception', e
>
> Note the "exec result in context" and my suggested changes to your 
> exception handling.
>
> Michael
>
>
> xkrja wrote:
>> Thanks for the reply.
>>
>> Below is a snippet of what I've got:
>>
>> def inputBox_KeyDown(s, e):
>>     root.message.Text = ''
>>     key = e.Key.value__
>>     result = root.inputBox.Text
>>     if key == 3: #If 'Enter' key is pressed
>>         try:
>>           root.message.Text = eval(result)
>>         except:
>>           exec result
>>          root = Application.Current.LoadRootVisual(UserControl(), 
>> "app.xaml")
>> sys.stdout = Writer(root.message)
>>
>> root.inputBox.KeyDown += inputBox_KeyDown
>>
>> Can't I just put everthing that is evaluated or executed in some kind of
>> global scope so that they can be accessed just like in the console? 
>> If not:
>> I looked a little at dictionaries but didn't really understand how to 
>> use
>> them in this case? Can someone give me a short example that can be 
>> used for
>> my case?
>>
>> Once again, thanks for all help!
>>
>>
>> Michael Foord-5 wrote:
>>  
>>> You've snipped the code so I can't see it exactly, but I'm pretty 
>>> sure you are doing this inside a method. This will create a new 
>>> 'scope' every time you enter the method and so you are creating a 
>>> local variable that disappears when you exit the method.
>>>
>>> When you exec you can provide a dictionary as a context for the 
>>> execution to happen in. If you store this as an instance member and 
>>> re-use the same execution context every time then changes will be 
>>> 'remembered'.
>>>
>>> Michael
>>>
>>>     
>>
>>   
>
>


-- 
http://www.ironpythoninaction.com/




More information about the Ironpython-users mailing list