To convert calculation output of Python script to web page we need BaseHTTPServer, a Python-based web server. With it, we could write any python code and display it in no time. It has advantage in form of simplicity, we don't need php to convert our result or typing it to static html code, we just used python alone (it's possible to write html and php code on python though).
This code below will display python script calculating value of a function (sin(x)+x^2) to web page. As it behave as web server too, we don't need apache or other web server to broadcast it.
Here the code. It's written in Python 2.7 on Mac OS X Lion with numpy module and sys, parser and basehttpserver built in module.
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServerAccess it using web browser in localhost:8080 from your computer running code above, or
import sys,parser
from math import *
import numpy as np
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
n=10
x=7
y = 'sin(x)+x**2'
z = parser.expr(y).compile()
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("Hi Folks, Aravir here ")
self.wfile.write("")
self.wfile.write("Hi Folks, Aravir here
")
self.wfile.write("
")
self.wfile.write("The value of ")
self.wfile.write(y )
self.wfile.write(" on x = " )
self.wfile.write(x)
self.wfile.write(" is " )
self.wfile.write(eval(z) )
self.wfile.write("")
if __name__=="__main__":
try:
server = HTTPServer(("", 8080), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
From python |