简体   繁体   English

如何使用上下文管理器例外

[英]How to use context manager with exceptions

I need to read file attachments from email messages. 我需要从电子邮件中读取文件附件。 I wanted to use context manager for resource management (connection should be closed) 我想使用上下文管理器进行资源管理(连接应该关闭)

@contextmanager
def some_f():
    conn = None
    try:
        for _ in xrange(CONNECTION_ERRORS_MAX):
            try:
                conn = POP3(self.pop3_host)
                conn.user(self.pop3_user)
                conn.pass_(self.pop3_password)
                logger.debug('connected {}', conn.getwelcome())
                _, msg_ids, _ = conn.uidl()
                yield (
                    (msg_id, self.files_from_msg(conn, file_batch_id, msg_id))
                    for msg_id, file_batch_id in
                    (ul.split(' ') for ul in msg_ids)
                    if not self.is_ignored(file_batch_id, msg_id)
                )
            except socket.error as e:
                if e.errno == errno.ECONNREFUSED:
                    pass
                else:
                    raise e
    finally:
        if conn:
            conn.quit()

So what this function supposed to do is try to connect to a email server, retry n-times if connection was refused if another socket error have happened then reraise it. 因此,此功能应该执行的操作是尝试连接到电子邮件服务器,如果发生另一个套接字错误,则如果拒绝连接,则重试n次,然后重新发送。 If retry attempts are exhausted then reraise connection refused error. 如果重试尝试已用尽,则重新引发连接拒绝错误。 After the consumer would consume all files close connection. 使用者使用完所有文件后将关闭连接。 Right now it gives generator didn't yield error. 现在,它使生成器没有产生错误。

Restructure your try-except clause so that it surrounds the minimum number of things. 重组try-except子句,使它包围最少的事物。 In the except clause, you can continue if necessary, and if it is not triggered, you should break from the for loop. 在except子句中,必要时可以continue ,如果未触发,则应从for循环中break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM