2016-12-23 21 views
0

如何在python中的PyCurl(libcurl)模塊中實現重試選項?同樣的事情也該效果:如何在PyCurl中實現重試選項

捲曲--retry 3 --retry延時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() 

回答

0

Pycurl不知道如何重新初始化您通過WRITEDATAWRITEFUNCTION選項提供的消費者,因此您的代碼必須執行重試邏輯:

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