好的,这是我的情况。我编写了一个带有textarea的HTML表单,该表单向python脚本提交了POST请求。我使用cgi库解析文本区域并将其拆分为一个数组。然后,我使用循环处理这些项目并在处理过程中打印它们。看来,即使我将print语句放入循环中,它也不会打印出来,直到整个过程完成并且脚本已退出。 html页面也将挂起,直到该过程完成。

Okay here's my situation. I wrote a HTML form with a textarea that submits a POST request to my python script. I use cgi library to parse the textarea and split it into an array. I then process the items using a loop and print items as they're processed. It seems that even though I put the print statement in the loop it doesn't print until the entire process is completed and the script has exited. The html page also hangs until the process is finished.


I have tried to flush the buffer using the sys.std.flush() after each print statement however it did not help.


Take a look at my code below. All help will be highly appreciated.


import cgi
import urllib2

form = cgi.FieldStorage()

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

list = h.split('\r\n');
    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("")
        data =
        if len(data) > 0:
            print "Data collected<br />"
    print "</body>"
except Exception:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<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;

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

 1 条回答