Skip to main content
 首页 » 编程设计

python之如何限制对 write 函数的 curl 调用次数

2025年05月04日9mate10pro

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

定义写函数:

conn.setopt(pycurl.WRITEFUNCTION, on_receive) 

感谢您的帮助!

请您参考如下方法:

这是一个应该可以工作的简单版本。构建 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"