奇怪的Python打印行为

发布于 2024-10-07 14:32:32 字数 335 浏览 0 评论 0原文

为什么这不打印任何内容:

for item in pipe.json["value"]["items"]:
    print item["pubDate"]
but this does:
for item in pipe.json["value"]["items"]:
   print item["pubDate"] + "\n"
p.s. the loop is running inside another loop.

pps 这是在谷歌应用程序引擎应用程序内部运行的。我查看了http响应,在第一种情况下它完全是空的。

why this does not print anything:

for item in pipe.json["value"]["items"]:
    print item["pubDate"]


but this does:

for item in pipe.json["value"]["items"]:
   print item["pubDate"] + "\n"


p.s. the loop is running inside another loop.

p.p.s. this is running inside google app engine application.i have looked at http response and it is completely empty in the first case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

淡淡绿茶香 2024-10-14 14:32:32

这可能是缓冲问题,在这种情况下刷新标准输出会有所帮助。

import sys
sys.stdout.flush()

It might be a problem with buffering, in which case flushing stdout would help.

import sys
sys.stdout.flush()
谈情不如逗狗 2024-10-14 14:32:32

您是否使用某种 wsgi 框架,或者只是尝试编写纯 CGI 代码(这是一个错误?)

您可能根本不想在这里使用 print ,而是使用您的框架的添加到响应的方法(对于 web 应用程序,self.response.out.write)。我的猜测是,如果没有额外的 \n,您会将所有这些数据写入 HTTP 标头,并且使用它您只会丢失输出的第一行。

Are you using some sort of wsgi framework, or just trying to write pure CGI code (which is a mistake?)

You probably don't want to be using print at all here, but rather using your framework's method of adding to the response (for webapp, self.response.out.write). My guess would be that without the extra \n, you're writing all of this data to the HTTP headers, and with it you're only losing the first line of your output.

久隐师 2024-10-14 14:32:32

在 GAE 上,如果您想使用 print 进行输出,则必须在任何打印之前打印一个空字符串,这样就不会发生此类问题:

print ""
print "something"

On GAE if you want to use print for output you'll have to print an empty string before any printing so that these kind of problems won't happen:

print ""
print "something"
小瓶盖 2024-10-14 14:32:32

这只是一个大胆的猜测,但如果 item['pubDate'] 是一个非字符串对象,则可能是特殊方法之间差异的结果。也许__str__ 方法什么也不返回,而__add__ 方法则执行不同的操作。

This is just a wild guess, but if item['pubDate'] is a non-string object it might a result of differences between special methods. Perhaps the __str__ method returns nothing, while the __add__ method does something different.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文