在t.cursor()方法中,对于一小部分ID,抛出Twython库中的异常。但是,每当异常发生时,我的代码中抛出的实际行是try / except块之后的for循环,这会阻止调用continue
。
如何在try块中抛出异常,不被except块捕获,然后在某些(大部分)不相关的代码中显示?
是的,这是一个401错误,但这只是Twitter API返回错误的代码。实际上,我正确地进行了身份验证。我也知道我可以将for块移到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.
答案 0 :(得分:1)
看起来t.cursor(...)
会返回一个实际上没有执行的生成器,直到你遍历它。虽然看起来连接发生在:
followers = t.cursor(t.get_followers_ids, id=id)
直到用for循环遍历生成器才会这样做。提到的here
如果您需要将处理延迟到稍后但仍希望捕获异常,请将生成器转换为列表。这将耗尽发电机并保存数据供以后使用。
followers = t.cursor(t.get_followers_ids, id=id)
followers = list(followers)
答案 1 :(得分:0)
你可能得到的东西
followers = t.cursor(t.get_followers_ids, id=id)
是一段代码,用于获取列表。但是因为这个光标是lazy,所以还没有执行Twyton代码。只有在第一次使用时才会执行acual获取代码....在抛出异常的行上。 所以也将它包装在异常处理中。