Unestablished连接和内容管理器

时间:2016-11-27 11:28:54

标签: python python-3.x with-statement

以下功能允许使用with-statment和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()

2 个答案:

答案 0 :(得分:0)

我想您可以将pop_conn.quit()放在try: pass作为相应的except行动:

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

答案 1 :(得分: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