-
-
Save zed/46a210950c95f73a75a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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" | |
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