urllib.read()结果返回空值
我正在尝试阅读&在 GAE 中打印 google URL 的结果。当我运行第一个程序时,输出为空白。然后我在打印 url 结果之前添加了一条打印语句并运行它。现在我得到了结果。
为什么程序1没有给出任何输出?
方案 1
import urllib
class MainHandler(webapp.RequestHandler):
def get(self):
url = urllib.urlopen("http://www.google.com/ig/calculator?hl=en&q=100EUR%3D%3FAUD")
result = url.read()
print result
方案 2
import urllib
class MainHandler(webapp.RequestHandler):
def get(self):
# Print something before print urllib result
print "Result -"
url = urllib.urlopen("http://www.google.com/ig/calculator?hl=en&q=100EUR%3D%3FAUD")
result = url.read()
print result
I'm trying to read & print the result from google's URL in GAE. When i run the first program, output was blank. then i have added a print statement before printing the url result and run it. Now i got the result.
Why the Program 1 doesn't give any output ?
Program 1
import urllib
class MainHandler(webapp.RequestHandler):
def get(self):
url = urllib.urlopen("http://www.google.com/ig/calculator?hl=en&q=100EUR%3D%3FAUD")
result = url.read()
print result
Program 2
import urllib
class MainHandler(webapp.RequestHandler):
def get(self):
# Print something before print urllib result
print "Result -"
url = urllib.urlopen("http://www.google.com/ig/calculator?hl=en&q=100EUR%3D%3FAUD")
result = url.read()
print result
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在 WSGI 应用程序内部使用
print
。永远不要在 WSGI 应用程序内部使用print
。发生的情况是,您的文本正在网络服务器期望看到标题的位置输出,因此您的输出不会按您的预期显示。
相反,您应该使用 self.response.out.write() 来将输出发送给用户,并使用logging.info 等来调试数据。
You're using
print
from inside a WSGI application. Never, ever useprint
from inside a WSGI application.What's happening is that your text is being output in the place where the webserver expects to see headers, so your output is not displayed as you expect.
Instead, you should use
self.response.out.write()
to send output to the user, andlogging.info
etc for debugging data.我以前遇到过这个问题。但目前还找不到确切的答案。
也许是
缓存机制
导致了这个问题,不确定。您需要执行
flush output
来打印数据:或者就像您所做的那样:
我想您在调试时会喜欢
logging
:或者
I met this issue before. But cannot find an exactly answer about it yet.
maybe the
cache mechanism
cause this issue, not sure.You need do
flush output
to print the data:or just do like the way you did:
I think you'll like
logging
when you are debugging:or