奇怪的Python打印行为
为什么这不打印任何内容:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可能是缓冲问题,在这种情况下刷新标准输出会有所帮助。
It might be a problem with buffering, in which case flushing stdout would help.
您是否使用某种 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.在 GAE 上,如果您想使用 print 进行输出,则必须在任何打印之前打印一个空字符串,这样就不会发生此类问题:
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:
这只是一个大胆的猜测,但如果 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.