Reputation: 6015
I'm doing a python class this semester, and I'd like to add graphical user interfaces to my programs in the form of web pages. Partly I can't be bothered to learn Tkinter, partly I'm just challenging myself, and partly I just like coding interfaces in HTML/JS.
I know the basics on creating HTTP servers with SimpleHTTPServer, but what I need is a way for my web pages to fire ajax commands to python scripts on the server, which will then be executes server side, and then receive the script output. Kind of like how Sage does things.
How can I create an extension for SimpleHTTPServer that I can then use to serve up the outputs of python scripts? I need a solution that's very general, so that given any python script I write, I can easily wrap it in some sort of interface, put it in the server's folder, and not have to do anything else but call it with AJAX, and my server will handle the rest.
My current idea is to have a ServerSideScript
class that my scripts can extend, with a single function called output
. Every script I have should contain a subclass of ServerSideScript named Script. When the server is asked to serve, for example, foo.py, it notices the extension and does something like:
if self.path[-3:]: == ".py":
return getScriptOutput(self.path)
...
def getScriptOutput(self, path):
from path import Script # obviously not going to work, since path is a string
return Script().output()
That can't work for the reason pointed out in the comment, I'm aware of things like the import_module function, but importing seems like an ugly way to do this to begin with.
What's recommended?
Upvotes: 1
Views: 1047
Reputation: 1123510
Python comes with batteries included; CGIHTTPServer
will run Python scripts using the CGI standard:
The
CGIHTTPServer
module defines a request-handler class, interface compatible withBaseHTTPServer.BaseHTTPRequestHandler
and inherits behavior fromSimpleHTTPServer.SimpleHTTPRequestHandler
but can also run CGI scripts.
It'll run Python scripts as long as they have a .py
or .pyw
extension, and are executable; other paths mapping to files are treated as regular files and have their content served instead.
You may be interested in the cgi
and cgitb
modules as well, to help ease CGI script development.
Upvotes: 4
Reputation: 9395
You might want to take a look at IPython notebooks - it essentially gives you a web-based interactive Python shell, which even integrates with matplotlib etc. You can save Python scripts as notebooks, add text inbetween statements etc.
You can also use the nbviewer if you want to share the output, but not the interactivity.
Upvotes: 1