【问题标题】:Python: continue after error libraryPython:错误库后继续
【发布时间】:2015-05-18 19:05:33
【问题描述】:

我有一个循环,它逐行读取文件并调用库。但是,有时该库会生成自己的错误消息,然后我的整个循环停止工作,因为它终止了循环。有没有办法可以控制库中的消息?收到此错误消息时如何使循环继续(即,如何检查此错误消息是否存在以便我可以跳过它)?

我得到的错误:

raise EchoNestAPIError(code, message, headers, http_status)
pyechonest.util.EchoNestAPIError: (u'Echo Nest API Error 5: The identifier specified does not exist [HTTP 200]',)

所以这是库中处理错误的代码部分:

class EchoNestAPIError(EchoNestException):
    """
    API Specific Errors.
    """
    def __init__(self, code, message, headers, http_status):
        if http_status:
            http_status_message_part = ' [HTTP %d]' % http_status
        else:
            http_status_message_part = ''
        self.http_status = http_status

        formatted_message = ('Echo Nest API Error %d: %s%s' %
                             (code, message, http_status_message_part),)
        super(EchoNestAPIError, self).__init__(code, formatted_message, headers)


class EchoNestIOError(EchoNestException):
    """
    URL and HTTP errors.
    """
    def __init__(self, code=None, error=None, headers=headers):
        formatted_message = ('Echo Nest IOError: %s' % headers,)
        super(EchoNestIOError, self).__init__(code, formatted_message, headers)

def get_successful_response(raw_json):
    if hasattr(raw_json, 'headers'):
        headers = raw_json.headers
    else:
        headers = {'Headers':'No Headers'}
    if hasattr(raw_json, 'getcode'):
        http_status = raw_json.getcode()
    else:
        http_status = None
    raw_json = raw_json.read()
    try:
        response_dict = json.loads(raw_json)
        status_dict = response_dict['response']['status']
        code = int(status_dict['code'])
        message = status_dict['message']
        if (code != 0):
            # do some cute exception handling
            raise EchoNestAPIError(code, message, headers, http_status)
        del response_dict['response']['status']
        return response_dict
    except ValueError:
        logger.debug(traceback.format_exc())
        raise EchoNestAPIError(-1, "Unknown error.", headers, http_status)

我尝试使用通用的“例外”而不定义任何内容,这适用于我达到 API 限制时,但仍然不适用于我问这个问题的错误。这个错误似乎来自同一个类。我不知道为什么它适用于限制错误,但不适用于其他错误。下面是API限制的错误:

raise EchoNestAPIError(code, message, headers, http_status)
pyechonest.util.EchoNestAPIError: (u'Echo Nest API Error 3: 3|You are limited to 120 accesses every minute. You might be eligible for a rate limit increase, go to http://developer.echonest.com/account/upgrade [HTTP 429]',)

【问题讨论】:

标签: python loops


【解决方案1】:

您在 try/except -block 中捕获异常。

例子:

with open(your_file, "r") as f:
    for line in f:
        try:
            api_call(line)
        except pyechonest.util.EchoNestAPIError:
            pass # or continue if you wish to skip processing this line.

try-block 中执行的每一行代码都可能导致异常,然后在except-block 中“捕获”(还有一个额外的finally-block,更多信息)在文档中)。上面的例子只是简单地抑制了异常,但这可能不是理想的解决方案。

异常是该语言的基本特性,您至少应该阅读official docs 才能开始使用。

【讨论】:

  • 谢谢,我以类似的方式尝试了您的解决方案,但它不会通过错误消息(您的也无法正常工作)。发生的事情是它打印出错误然后停止。我不认为问题在于如何跳过它,而是如何检测导致问题的错误消息。它似乎没有捕获它以传递或继续循环(我尝试在异常部分打印一些文本,但它从不打印它)。我还尝试在文件顶部包含以下内容:“from pyechonest import util”或除外部分的变体(例如“util.EchoNestAPIError”)
  • @user40037 除非您显示有问题的代码,否则无法知道问题所在。
  • 我把它添加到我原来的问题中:-)
猜你喜欢
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
相关资源
最近更新 更多