Skip to content

Instantly share code, notes, and snippets.

@zed
Last active August 29, 2015 13:57
Show Gist options
  • Save zed/46a210950c95f73a75a6 to your computer and use it in GitHub Desktop.
Save zed/46a210950c95f73a75a6 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"""cgi: stream subprocess output."""
import cgitb; cgitb.enable()
import cgi
import sys
from subprocess import Popen, PIPE, STDOUT
cmd = [sys.executable or 'python', "-u", "-c", """
# generate some output
import time
for i in range(50):
print("<%d>" % i)
time.sleep(.1)
"""]
def print_chunk(chunk):
sys.stdout.write(chunk)
sys.stdout.flush()
# print http headers
print "Content-Type: text/html"
print
sys.stdout.flush()
# print http body: output is displayed in "real time" +/- buffering
print_chunk("<!doctype html>"
"<title>Stream subprocess output</title>")
source_code = open(__file__).read()
print_chunk("<pre><code>%s</code></pre>\n" % cgi.escape(source_code))
p = Popen(cmd, stdout=PIPE, stderr=STDOUT, bufsize=1)
for line in iter(p.stdout.readline, ''):
print_chunk("<pre>%s</pre>\n" % cgi.escape(line.rstrip('\n')))
# last chunk
print_chunk("") # empty
# end of source code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment