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.

  • 80 / 4, or any other type of basic calculation, thus we can use it as a calculator
  • len("Hellow World!") – we can use it to compute the length of a given string
  • "Hello World".count("o") to find out how often a particular character shows up in a given string
  • … and many more ( ideas ? )

Here is the code:

   1: #!/usr/bin/python
   2:  
   3: import cgitb; cgitb.enable()
   4:  
   5: import cgi
   6: form = cgi.FieldStorage()
   7:  
   8: expr = form.getvalue('expr', None)
   9:  
  10:  
  11:  
  12: if expr != None:
  13:     try: output = expr + " => " + str(eval(expr))
  14:     except Exception,e: output = "<font color=\"red\">%s => %s</font>" % (expr,e)
  15: else: output = ""
  16:  
  17: print '''Content-type: text/html
  18:  
  19: <html>
  20:   <head>
  21:     <title>Python Expression Evaluator</title>
  22:   </head>
  23:   <body>
  24:     <h1>Python Expression Evaluator</h1>
  25:     <div>%s</div>
  26:     <br>
  27:     <form action='py_eval.py'>
  28:     Expression <input type='text' name='expr' />
  29:     <input type='submit' />
  30:     </form>
  31:   </body>
  32: </html>
  33: ''' % 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

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

to just

   1: 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. 5. … ?

Happy New Year 2012 everyone !

Happy New Year 2012 everyone ! I hope you have had a good start into the New Year and hopefully don’t start it with too many items sitting in your in-box and waiting for you to get you into the same hectic and trouble like every year.

Still looking for some good New Year resolutions ? Check out this Lifehacker article: Top 10 Easy-to-Keep Resolutions for This New Year. And here are some more general hints and insights about making New Year’s resolutions: The Science Behind New Year’s Resolutions (and How to Use It to Achieve Yours)

Don’t need any of those ? I don’t have any but I actually like this one from Garfield.

May be you are just curious about the most successful blog postings on Lifehacker last year ? Here they are: This Is the Best of Lifehacker 2011: about How-To guides, DIY projects, photography, Mac and linux downloads, desktops and workspaces, browser extensions and Android apps. How about starting an information diet this year ? Or some very basic means to improve your health: “A Half-Hour Walk Can Make a Big Difference, Even If It’s Your Only Activity” ?

Many seem to say the world will end this year: the Bible, the Maya Calendar, Nostradamus, http://www.polereversal.com/. Most likely this will be a mis-interpretation of “information” one can find there or elsewhere; don’t forget my last posting from last year: Common knowledge doesn’t exist. : It is more a question of belief which evidence you accept and who you trust … and how you interpret information.

Nevertheless, even if the world would end this year, let’s just continue to do what we do now, let’s do it right and with our full power, let’s follow the philosophy of Martin Luther, to whom the following quote was attributed:

“If I knew that tomorrow was the end of the world, I would plant an apple tree today.”

Image from Wikiquote.

2011 in review

The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.

Here’s an excerpt:

The concert hall at the Syndey Opera House holds 2,700 people. This blog was viewed about 20,000 times in 2011. If it were a concert at Sydney Opera House, it would take about 7 sold-out performances for that many people to see it.

Click here to see the complete report.

Follow

Get every new post delivered to your Inbox.