2009-10-23 206 views
3

程序自動重新啓動程序是這樣的:時發生錯誤

HEADER CODE 
urllib2.initialization() 
try: 
    while True: 
     urllib2.read(somebytes) 
     urllib2.read(somebytes) 
     urllib2.read(somebytes) 
     ... 
except Exception, e: 
    print e 
FOOTER CODE 

發生錯誤時我的問題是(超時,通過對等連接復位等),如何從urllib2.initialization重新啓動()代替現有主程序並重新從頭文件重新啓動?

回答

2

簡單的方式

HEADER CODE 
attempts = 5 
for attempt in xrange(attempts): 
    urllib2.initialization() 
    try: 
     while True: 
      urllib2.read(somebytes) 
      urllib2.read(somebytes) 
      urllib2.read(somebytes) 
      ... 
    except Exception, e: 
     print e 
    else: 
     break 
FOOTER CODE 
4

如何將它包裝在另一個循環中?

HEADER CODE 
restart = True 
while restart == True: 
    urllib2.initialization() 
    try: 
     while True: 
      restart = False 
      urllib2.read(somebytes) 
      urllib2.read(somebytes) 
      urllib2.read(somebytes) 
      ... 
    except Exception, e: 
     restart = True 
     print e 
FOOTER CODE 
5

你可以在 「而不是做」 循環包裝你的代碼:與嘗試限制

#!/usr/bin/env python 

HEADER CODE 
done=False 
while not done: 
    try: 
     urllib2.initialization() 
     while True: 
      # I assume you have code to break out of this loop 
      urllib2.read(somebytes) 
      urllib2.read(somebytes) 
      urllib2.read(somebytes) 
      ... 
    except Exception, e: # Try to be more specific about the execeptions 
          # you wish to catch here 
     print e 
    else: 
    # This block is only executed if the try-block executes without 
    # raising an exception 
     done=True 
FOOTER CODE