在web.py中动态打印

时间:2011-07-18 11:31:24

标签: python cgi web.py

我正在将应用程序从cgi转移到web.py.我得到结果并使用cgi中的简单print语句动态打印它们。因此,在页面完成加载之前已打印结果。在web.py中,我有一个return语句,无法弄清楚我是如何实现同样的。

示例cgi代码:

print "<p><b>Displaying Search Results</b></p>"
print "<table>"
cmd = subprocess.Popen(["find", location ,"-name", fileName], stdout=subprocess.PIPE)
for line in cmd.stdout:
    tableData=line.rstrip("\n")
    tableRow="<tr><td>tableData</td></tr>"
    print tableRow
print "</table>"

上面的代码会在生成时一次打印一行。我如何为web.py ???

编写相同的内容

2 个答案:

答案 0 :(得分:2)

使用你追加的字符串并最终返回:

s = "My page with..."
s += "More data"
for y in x:
    s += "And this!"
return s

http://webpy.org/cookbook/streaming_large_files中描述的产生数据的能力 有一些问题,你必须设置一些标题,你不能混合returnyield,因为你把它作为一个生成器。

设置标题的一部分,您使用:yield "Some more data",类似于在CGI脚本中打印。

答案 1 :(得分:1)

即使您可以通过使用连接和单个返回替换print来简化移植,但请考虑使用模板引擎(web.py具有名为Templetor的内置模板引擎)。

将逻辑与演示文稿分开可让您更改其中一个,而无需更容易地考虑另一个。