2016-11-27 31 views
0

以下函數允許使用with-statment和彈出連接。但是如果連接沒有建立,quit()終於會引發異常。這怎麼解決?未建立連接和內容管理器

@contextmanager 
def pop_connect(server, user, password, timeout, use_SSL=False): 
    try: 
     pop = poplib.POP3_SSL if use_SSL else poplib.POP3 
     pop_conn = pop(server, timeout=timeout) 
     pop_conn.pass_(password) 
     yield pop_conn 
    except poplib.error_proto as pop_error: 
     print('Authentication for receiving emails failed:{}'.format(pop_error)) 
    except OSError as os_error: 
     print('Name resolution or connection failed:{}'.format(os_error)) 
    finally: 
      pop_conn.quit() 

回答

0

我想你可以把你的pop_conn.quit()try:pass對應except行動:

finally: 
    try: 
     pop_conn.quit() 
    except <WhaterverException>: 
     pass 
0

解決的辦法是重新拋出的處理程序的異常。上下文管理者除了收益率不高外:

@contextmanager 
def pop_connect(server, user, password, timeout, use_SSL=False): 
    try: 
     pop_conn = poplib.POP3_SSL(server,timeout=timeout) if use_SSL else poplib.POP3_SSL(server,timeout=timeout) 
     pop_conn.user(user) 
     pop_conn.pass_(password) 
     yield pop_conn 
    except poplib.error_proto as pop_error: 
     print('Receiving mail failed:{}'.format(pop_error)) 
     raise 
    except OSError as os_error: 
     print('Name resolution or connection failed:{}'.format(os_error)) 
     raise 
    finally: 
     try: 
      pop_conn.quit() 
     except UnboundLocalError: 
      pass