简体   繁体   English

Python cgi脚本仅在完成后才在浏览器中显示输出

[英]Python cgi script displays output in the browser only after its completion

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. 我注意到python cgi脚本仅在完成执行后才显示输出。有没有办法,我可以使该脚本继续执行并连续打印结果。 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. 我发现,如果我在Apache中这样运行脚本“ abc.py”,则会连续显示输出(脚本继续执行),但是从另一个脚本调用脚本时不起作用。

Below is the code :- (abc.py) 下面是代码:-(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. 我想从另一个CGI脚本运行此脚本。 Now when I am calling this script (in Apache using below script), the output is printed only after its completion. 现在,当我调用此脚本(在Apache中使用以下脚本)时,仅在完成后才输出输出。 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()

Working code 工作代码

abc.py 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM