web.py 中的动态打印
我正在将应用程序从 cgi 转移到 web.py。我得到结果并使用 cgi 中的简单打印语句动态打印它们。因此,在页面加载完成之前,结果就已经打印出来了。在 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 编写相同的内容???
I'm shifting an application from cgi to web.py. I get results and print them dynamically with a simple print statement in cgi. So the results have been printed before the page has completed loading. In web.py, I have a return statement and can't figure out how I can achieve the same.
Sample cgi code:
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>"
The above code would print a row at a time as it is generated. How do I write the same for web.py???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要么使用附加到最后返回的字符串:
要么生成数据的能力,如 http://webpy 中所述。 org/cookbook/streaming_large_files
有一些问题,您必须设置一些标头,并且不能混合
return
和yield
因为您将其设为生成器。除了设置标题之外,您还可以使用:
yield "Some more data"
,类似于 CGI 脚本中的打印。Either use a string which you append to and finally return:
Or the ability to yield data, described in http://webpy.org/cookbook/streaming_large_files
There are some gotchas, you have to set some headers and you can't mix
return
andyield
since you make it a generator.A part from setting the headers, you'd use:
yield "Some more data"
, similar to print in your CGI-script.尽管您可以通过用串联和单个返回替换
print
来简化移植,但请考虑使用模板引擎(web.py 有一个名为 Templetor)。将逻辑与表示分离使您可以更轻松地更改其中之一,而无需考虑另一个。
Even though you can ease porting by replacing
print
s with concatenation and a single return, consider using a templating engine (web.py has a built-in templating engine named Templetor).Separating the logic from the presentation allows you to change one of them without thinking of the other one more easily.