urllib.read()结果返回空值

发布于 2024-12-21 01:19:24 字数 704 浏览 2 评论 0原文

我正在尝试阅读&在 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 技术交流群。

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

发布评论

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

评论(2

情绪失控 2024-12-28 01:19:24

您正在 WSGI 应用程序内部使用 print。永远不要在 WSGI 应用程序内部使用 print

发生的情况是,您的文本正在网络服务器期望看到标题的位置输出,因此您的输出不会按您的预期显示。

相反,您应该使用 self.response.out.write() 来将输出发送给用户,并使用logging.info 等来调试数据。

You're using print from inside a WSGI application. Never, ever use print 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, and logging.info etc for debugging data.

累赘 2024-12-28 01:19:24

我以前遇到过这个问题。但目前还找不到确切的答案。
也许是缓存机制导致了这个问题,不确定。
您需要执行flush output来打印数据:

import sys
sys.stdout.flush()

或者就像您所做的那样:

print "*" * 10
print data

我想您在调试时会喜欢logging

logging.debug('A debug message here')

或者

logging.info('The result is: %s', yourResultData)

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:

import sys
sys.stdout.flush()

or just do like the way you did:

print "*" * 10
print data

I think you'll like logging when you are debugging:

logging.debug('A debug message here')

or

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