Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 10th, 2012  |  syntax: None  |  size: 1.24 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to make failover in python?
  2. again = 1
  3.  start = 1
  4.  try:
  5.    def countthis():
  6.           for i in range (start,200):
  7.               again = i
  8.               print i
  9.  except:
  10.     print "Failure occured, I will try again"
  11.     start = again
  12.     countthis.run()
  13.        
  14. def countthis(start=0, end=100):
  15.     for i in range(start, end):
  16.         print i
  17.         if i == 5:
  18.             raise Exception('5 failed')
  19.         yield i
  20.        
  21. ret = 0
  22. end = 100
  23. while ret < end - 1:
  24.     try:
  25.         for i in countthis(start=ret, end=end):
  26.             ret = i
  27.     except Exception, ex:
  28.         print ex
  29.         # when 5 reached, an exception will be raised, so here we restart at '6'
  30.         ret = ret + 2
  31.        
  32. 0
  33. 1
  34. 2
  35. 3
  36. 4
  37. 5
  38. 5 failed
  39. 6
  40. 7
  41. ......
  42. 99
  43.        
  44. def f():
  45.     print "f called: ",
  46.  
  47.     import random
  48.     x = random.randint(0, 10) / 8
  49.  
  50.     print "1/x =", 1/x
  51.  
  52. while True:
  53.     try:
  54.         f()
  55.         break
  56.     except ZeroDivisionError:
  57.         print "f failed"
  58.         continue
  59.        
  60. def f():
  61.     import random
  62.  
  63.     for i in range(1, 10):
  64.         while True:
  65.             try:
  66.                 print i,
  67.  
  68.                 # do something with i:
  69.                 print 1 / (i // random.randint(0, 8))
  70.                 break
  71.             except ZeroDivisionError:
  72.                 continue
  73.  
  74.  
  75. f()