0

在 t.cursor() 方法中,Twython 库中的一小部分 id 会引发异常。但是,无论何时发生异常,在我的代码中引发异常的实际行是 try/except 块之后的 for 循环,这会阻止continue调用 。

如何在 try 块中抛出异常,而不是被 except 块捕获,然后在一些(大部分)不相关的代码中出现?

是的,这是一个 401 错误,但这只是 Twitter API 返回错误代码。实际上,我正确地进行了身份验证。我也知道我可以将 except 块移到 for 循环之后,但我只想知道这到底是怎么发生的。

from twython import Twython
t = Twython(...)

# ...

for id in ids:
    try:
        # exception is truly caused by the following line
        followers = t.cursor(t.get_followers_ids, id=id)
    except:
        # this block is never run
        print("Exception with user " + str(id))
        continue

    # this line actually throws the exception, inexplicably
    for follower_id in followers:
        values.append((follower_id, id, scrape_datetime))

    # ...

追溯:

Traceback (most recent call last):
File "/root/twitter/nightly.py", line 5, in <module>
    t.get_followers(t.current_tweeters)
File "/root/twitter/tweets.py", line 81, in get_followers
    for follower_id in followers:
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/api.py", line 398, in cursor
content = function(**params)
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/endpoints.py", line 212, in get_followers_ids
return self.get('followers/ids', params=params)
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/api.py", line 231, in get
return self.request(endpoint, params=params, version=version)
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/api.py", line 225, in request
content = self._request(url, method=method, params=params, api_call=url)
File "/usr/local/lib/python3.3/dist-packages/twython-3.0.0-py3.3.egg/twython/api.py", line 195, in _request
retry_after=response.headers.get('retry-after'))
twython.exceptions.TwythonAuthError: Twitter API returned a 401 (Unauthorized), An error occurred processing your request.
4

2 回答 2

1

看起来t.cursor(...)返回一个生成器,直到你迭代它才真正执行。虽然看起来连接发生在:

followers = t.cursor(t.get_followers_ids, id=id)

直到你用你的 for 循环遍历生成器。有点提到这里

如果您需要推迟处理,但仍想捕获异常,请将生成器转换为列表。这将耗尽生成器并保存数据以备后用。

followers = t.cursor(t.get_followers_ids, id=id)
followers = list(followers)
于 2013-09-04T17:52:12.237 回答
0

你可能得到了什么

followers = t.cursor(t.get_followers_ids, id=id)

是一段代码的光标,它将获取您的列表。但是因为这个游标是惰性的,所以还没有执行任何 Twyton 代码。acual fetching 代码仅在第一次使用时执行....在抛出异常的行。因此,也将其包装在异常处理中。

于 2013-09-04T17:54:39.483 回答