Is resume() function available in python 2.7?

222 views Asked by At

Is there any resume() function in python. I need to apply it on my program. need proper explanation I searched a lot but didn't get it.

Here is my code where I need to place the resume function.

try:
    soup = BeautifulSoup(urllib2.urlopen(url))
    abc  =  soup.find('div', attrs={})
    link =    abc.find('a')['href']
    #result is dictionary
    results['Link'] =  "http://{0}".format(link)
    print results
    #pause.minute(1)
    #time.sleep(10)

except Exception:
    print "socket error continuing the process"
    time.sleep(4)
    #pause.minute(1)
    #break

I apply pause, time.stamp and break but not getting the required result. If any error appears in try then I want to pause the program. try block is already inside loop.

1

There are 1 answers

0
jfs On BEST ANSWER

To resume the code in case of an exception, put it inside a loop:

import time
import urllib2
from bs4 import BeautifulSoup # $ pip install beautifulsoup4

for _ in range(max_retries):
   try:
       r = urllib2.urlopen(url) 
       encoding = r.info().getparam('charset')
       html = r.read()
   except Exception as e:
       last_error = e
       time.sleep(retry_timeout)
   else:
       break
else: # all max_retries attempts failed 
   raise last_error 

soup = BeautifulSoup(html, from_encoding=encoding)
# ...