Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web-ifing a python command line script?

Tags:

python

This is my first questions here, so I hope it will be done correctly ;)

I've been assigned the task to give a web interface to some "home made" python script. This script is used to check some web sites/applications availability, via curl commands. A very important aspect of this script is that it gives its results in real-time, writing line by line to the standard output.

By giving a web interface to this script, the main goal is that the script can be easily used from anywhere, for example via a smartphone. So the web interface must be quite basic, and work "plugin-free".

My problem is that most solutions I thought or found on the web (ajax, django, even a simple post) seem to be needing a full generation of the page before sending it to the browser, losing this important "real-time" aspect.

Any idea on how to do this properly ?

Thanks in advance.

like image 250
Lenn Avatar asked Jul 20 '10 11:07

Lenn


1 Answers

A sketch for a solution:

Create an HTML file which contains the layout for your web page, with a dedicated DIV for the output of the script:

<html>
<body>
<div id="scriptoutput"></div>
<script type="text/javascript" src="localhost:8000/runscript"/>
</body>
</html>

This HTML file can be served using any server you wish.

Now, write a simple http server which runs the script and converts each line to a javascript command (example in python):

import os
f = os.popen('ping 127.0.0.1')
for i in range(30):
  ln = f.readline() 
  print "document.getElementById('scriptoutput').innerHTML += '<pre>%s</pre><br/>';" % ln

You can use any CGI/WSGI server for the task, or if performance is not crucial, even use Python's own BaseHTTPServer class.

This would do the trick, as most browsers parse and execute Javascript scripts as they are received (and not only when the request is completed) - note that no polling or server-side storage is needed!

like image 56
adamk Avatar answered Sep 22 '22 06:09

adamk