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

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


xkrja wrote:
> Thanks for the reply. This is what I have:
>
> def inputBox_KeyDown(s, e):
>     root.message.Text = ''
>     key = e.Key.value__
>     if key == 3:
>         result = eval(root.inputBox.Text)
>         root.message.Text = str(result)
>
> eval() seems to work sometimes. For example if the text in the textbox is
> 1+1 . But if the text for example is a=1 i get an error "Unexpected token
> '=' " (This is in Ironpython studio). I guess it is because a=1 is not an
> expression. What should I use then? What if I don't know what the user will
> type in? 
>
> Thanks again!
>   
If you only *want* an expression then a statement is indeed invalid. As 
you are accepting arbitrary user input then you will need error handling 
around the eval for when the user enters nonsense (as they are 
guaranteed to at some point...). You probably want a way to signal to 
the user what went wrong - perhaps a system message box.

Michael

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




More information about the Ironpython-users mailing list