2

我正在尝试限制调用此 WRITEFUNCTION 的次数。有什么办法可以做到吗?

定义写函数:

conn.setopt(pycurl.WRITEFUNCTION, on_receive)

谢谢您的帮助!

4

1 回答 1

1

这是一个肮脏的简单版本,应该可以工作。构建 PycURL 以测试并找到更好的方法。

import pycurl, json

STREAM_URL = "http://chirpstream.twitter.com/2b/user.json"

USER = "segphault"
PASS = "XXXXXXXXX"

class LimitError(Exception): pass

counter = 0
limit = 10
def on_receive(data):
    global counter
    if counter < 10:
        print data
        counter += 1
    else:
        raise LimitError    
conn = pycurl.Curl()
conn.setopt(pycurl.USERPWD, "%s:%s" % (USER, PASS))
conn.setopt(pycurl.URL, STREAM_URL)
conn.setopt(pycurl.WRITEFUNCTION, on_receive)

try:
    conn.perform()
    print "Exited Normally"
except LimitError:
    print "Reached limit, exiting"
except pycurl.error:
    if counter == limit:
        print "pycurl expected error, nothing to worry about"
    else:
        raise
finally:
    conn.close()

print "All done"
于 2011-01-17T05:18:20.607 回答