未建立的连接和内容管理器

Unestablished connection and content manager

以下函数允许使用 with-statement 和 pop 连接。但是如果没有建立连接,finally 中的 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()

我想你可以把你的 pop_conn.quit() 放在 try: 中,pass 作为对应的 except 动作:

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

解决方案是重新抛出处理程序中的异常。 contextmanager 比不排除产量:

@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