Search This Blog

Saturday, November 10, 2018

Example of python CGI calling another script

sleep.py:
#!/usr/bin/python
import sys, time

for i in range(10):
    print str(i)
    sys.stdout.flush()
    time.sleep(1)

call-sleep.py
#!/usr/bin/python
import sys, time
import subprocess
import cgi, cgitb
print "Content-Type: text/html\n\n"
print '<html><body>'
PIPE = subprocess.PIPE
pd = subprocess.Popen(['./sleep.py'],
                        stdout=PIPE, stderr=PIPE)
while True:
    output = pd.stdout.read(1)
    if output == '' and pd.poll() != None:
      break
    if output != '':
      sys.stdout.write(output)
      sys.stdout.flush()