Python:CGI更新网页在脚本退出前

2 投票
1 回答
2146 浏览
提问于 2025-04-16 13:12

好的,先说说我的情况。我写了一个HTML表单,里面有一个文本区域,可以提交一个POST请求到我的Python脚本。我使用cgi库来解析这个文本区域的内容,并把它分割成一个数组。接着,我用一个循环来处理这些项目,并在处理时打印出来。但是,奇怪的是,尽管我在循环里加了打印语句,它却等到整个过程完成、脚本退出后才会打印出来。而且,HTML页面在这个过程中也会卡住,直到处理完成。

我尝试在每个打印语句后面使用sys.std.flush()来刷新缓冲区,但似乎没有什么效果。

请看看我下面的代码。任何帮助都非常感谢。

提前谢谢你。

import cgi
import urllib2

form = cgi.FieldStorage()

h = str(form.getvalue('list'))

list = h.split('\r\n');
try:
    print "Content-Type: text/html\n\n"
    print "<head>"
    print "<title>Age</title>"
    print "</head>"
    print "<body>"
    for x in range(0, len(list)):
        print "List: %s" %list[x] + "</br>"
        sck = urllib2.urlopen("http://www.google.com/")
        data = sck.read()
        if len(data) > 0:
            print "Data collected<br />"
        sck.close
    print "</body>"
except Exception:
    pass


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Python Demo</title>
<style type="text/css">
    #form {
        width: 400px;
    }

    #form label {
        display: block;
    }

    #form textarea {
        width: 100%;
    }

    #form input {
        display: block;
        margin-top: 10px;
    }
</style>
</head>

<body>
<div id="form">
<form id="form1" name="form1" method="post" action="demo.py">
    <label for="list">List:</label>
    <textarea name="list" id="list" cols="50" rows="10"></textarea>
    <input type="submit" name="submit" id="submit" value="Submit" />
</form>
</div>
</body>
</html>

1 个回答

1

看这里

http://docs.python.org/library/cgi.html#common-problems-and-solutions

它说大多数HTTP服务器会把CGI脚本的输出先缓存起来,直到脚本执行完毕。

撰写回答