1

I noticed that the python cgi script displays the output only after it has completed its execution, Is there a way, I could make the script to continue its execution and print the results continously. I found that If I run the script "abc.py" as such in Apache, then output is displayed continously (script continuing its execution), however on calling script from another script doesn't works.

Below is the code :- (abc.py)

import sys, time
#sys.stdout.write('Content-Type: text/html;charset=utf-8\r\n\r\n')

#print '<html><body>'
for i in range(10):
    print '<div>%i</div>'%i
    sys.stdout.flush()
    time.sleep(1)

I want to run this script from another CGI script. Now when I am calling this script (in Apache using below script), the output is printed only after its completion. Is there a way to fix it.

print 'Content-Type: text/html;charset=utf-8\r\n\r\n'
print '<html><body>'

PIPE = subprocess.PIPE
pd = subprocess.Popen(['abc.py'],
  stdout=PIPE, stderr=PIPE)
stdou, stder = pd.communicate()
sys.stdout.write(stdou)
sys.stdout.flush()
1
  • Are you sure it's not the browser waiting for the closing </html> tag to render the output? Commented May 1, 2013 at 11:08

1 Answer 1

2

Working code

abc.py

#!/grid/common/bin/python
import sys, time

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

Main script

#!/grid/common/bin/python
import sys, time
import subprocess
import cgi, cgitb
cgitb.enable()

print 'Content-Type: text/html;charset=utf-8\r\n\r\n'

print '<html><body>'

PIPE = subprocess.PIPE
pd = subprocess.Popen(['abc.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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.