You are invited to Log in or Register a free Frihost Account!

A Python Expression Evaluator

To start going with my first little Python based web application here I came up with Python Expression Evaluator. What is does ? The name says it all: it evaluates Python expressions, which the user can enter into a form and send to the server where this little 25-liner does its work and returns the result plus all the HTML code to render it nicely on the user's screen:

It allows the user to type in any type of Python expression, like e.g.

Here is the code:


import cgitb; cgitb.enable()

import cgi
form = cgi.FieldStorage()

expr = form.getvalue('expr', None)

if expr != None:
    try: output = expr + " => " + str(eval(expr))
    except Exception,e: output = "<font color=\"red\">%s => %s</font>" % (expr,e)
else: output = ""

print '''Content-type: text/html

    <title>Python Expression Evaluator</title>
    <h1>Python Expression Evaluator</h1>
    <form action=''>
    Expression <input type='text' name='expr' />
    <input type='submit' />
''' % output

Let's decipher what it does:

    1. Let the script know we are using Python code
    2. Import cgitb module and enable CGI Tracebacks to nicely show error messages on the screen rather than in the web server log file. Not really needed here since my little script basically catches all sorts of exceptions, as we will see in a minute. Thanks to Magnus Lie Hetland and his great book "Beginning Python: From Novice to Professional, Second Edition" for this tip !
    3. Import cgi module, mainly used to retrieve values sent to the server
    4. Implement the cgi FieldStorage to retrieve values sent to the server
    5. Evaluate the expression sent to the server. With the help of exception handling all possible exceptions are handled and translated to a message ( variable output ) sent back to the user
    6. Generate the HTML for the user frontend and insert the output message; either the output from the eval() or the exception message.

Try the expression ("10/0") to see how Python's exception handling catches that error. If I would remove my own exception handling from the code and change it from

if expr != None:
    try: output = expr + " => " + str(eval(expr))
    except Exception,e: output = "<font color=\"red\">%s => %s</font>" % (expr,e)
else: output = ""

to just

output = expr + " => " + str(eval(expr))

then the cgitb module would kick in and transform the unhandled exception into a message shown in the browser, like here for example:

Nice, so far.

What enhancements can we think of to enhance this little tool ? Here are my ideas, any more to come ?

    1. Support multi-line Python code
    2. Support regular expressions
    3. Support expression storage & retrieval ( partially works thru your browser; try to hit the Down while entry field has focus )
    4. Support a more dynamic user interface
    5. ... ?

1 blog comments below

I just played with this a little, and wondered if I could do things like find out what version of python was in use. Theoretically I might also be able to do things like call exec, which could create a security problem. But it turned out I got syntax errors unexpectedly, so I tried simper stuff. It turns out the variable dir is a string, so can't use that. I was able to use () and {} and [], but when I put values inside, it's not working in many cases. I did get 1 in [1,2] to return True.

I'm wondering if some of the stuff that failed was due to security protections or was accidental.

*** this just in ***

Ok, I could just enter globals() or locals() as the expression and it worked, but it seems to be sparse, so probably sandboxed at least to some extent.
SonLight on Sat Oct 15, 2016 7:30 pm

© 2005-2011 Frihost, forums powered by phpBB.