如何在PyCurl中实现重试选项 [英] How to implement a retry option in PyCurl
本文介绍了如何在PyCurl中实现重试选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在python的PyCurl(libcurl)模块内实现重试选项?类似于以下效果:
How could I implement a retry option within the PyCurl (libcurl) module in python? Something similar to the effect of:
curl --retry 3 --retry-delay 5' http://somesite.com/somefile '
curl --retry 3 --retry-delay 5 'http://somesite.com/somefile'
当前代码:
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, 'http://somesite.com/somefile')
with open('output.txt','w') as f:
c.setopt(c.WRITEFUNCTION, f.write)
c.perform()
推荐答案
Pycurl不知道如何通过 WRITEDATA
或 WRITEFUNCTION
重新初始化您提供的使用者选项,因此您的代码必须实现重试逻辑:
Pycurl doesn't know how to re-initialize the consumer you supply through the WRITEDATA
or WRITEFUNCTION
options, so your code has to implement the retry logic:
retries_left = 3
delay_between_retries = 5 # seconds
success = False
c = pycurl.Curl()
c.setopt(c.URL, 'http://somesite.com/somefile')
while retries_left > 0:
try:
with open('output.txt', 'w') as f:
c.setopt(c.WRITEFUNCTION, f.write)
c.perform()
success = True
break
except BaseException as e:
retries_left -= 1
time.sleep(delay_between_retries)
# check success
这篇关于如何在PyCurl中实现重试选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文