在python中读取HTTP流

在python中读取HTTP流,python,twitter,Python,Twitter,我试图读取Twitter流API的输出,但遇到了一些问题。以下是我目前的代码: from urllib2 import * import StringIO password_mgr = HTTPPasswordMgrWithDefaultRealm() url = "https://stream.twitter.com/1/statuses/sample.json" password_mgr.add_password(None, url, 'myusername', 'mypassword')

我试图读取Twitter流API的输出,但遇到了一些问题。以下是我目前的代码:

from urllib2 import *
import StringIO

password_mgr = HTTPPasswordMgrWithDefaultRealm()
url = "https://stream.twitter.com/1/statuses/sample.json"
password_mgr.add_password(None, url, 'myusername', 'mypassword')
h = HTTPBasicAuthHandler(password_mgr)
opener = build_opener(h)
page = opener.open(url)
io = StringIO(page.read())
print io.getvalue()
io.close()

最初我只使用了
page.read()
,但导致我的控制台一直打印流,而不会返回到代码。我现在尝试使用StringIO将其作为一个流进行处理,并以增量方式打印出来,但当我这样做时,我什么也得不到,并且这个过程保持不变。有更好的方法吗?

我听说“请求”模块有很多优点:


我听说“请求”模块有很多优点:


请阅读流媒体请求


请阅读“流媒体请求”

我极力推荐我极力推荐
import json
import requests

r = requests.get('https://httpbin.org/stream/20', stream=True)

if r.encoding is None:
    r.encoding = 'utf-8'

for line in r.iter_lines(decode_unicode=True):
    if line:
        print(json.loads(line))