【问题标题】:How can I improve my error handling so the exception StopIteration in Tweepy is processed correctly and execution can continue?如何改进我的错误处理,以便正确处理 Tweepy 中的异常 StopIteration 并且可以继续执行?
【发布时间】:2020-10-25 13:17:50
【问题描述】:

我有以下函数来获取 Twitter 关注者并将它们写入 MySQL 数据库。我的问题是我的错误处理不能很好地处理 StopIteration 情况。 当我执行代码时,它确实根据 API 限制将详细信息写入数据库,但最后它会生成下面的错误,因此不会执行进一步的代码。 如何改进我的错误处理以便正确处理异常?

StopIteration:上述异常是导致 以下异常:RuntimeError

def limit_handled(cursor):
    while True:
        try:
            yield cursor.next()
        except tweepy.RateLimitError:
            time.sleep(15 * 60)
def writeFollowersToDB(TwitterAPI,DBConnection,SocialHandle ="Microsoft",DatabaseTable="twitter"):
    AboutMe = TwitterAPI.get_user(SocialHandle)
    #print(AboutMe)
    DBCursor=mydb.cursor()
    #Create the SQL INSERT
    SQLInsert="INSERT INTO "+ DatabaseTable + " (SourceHandle,SourceHandleFollowersCount,SourceHandleFollowingCount, Action,DestinationHandle,DestinationHandleFollowersCount,DestinationPublishedLocation,DestinationWeb,CrawlDate) VALUES (%s, %s, %s,%s,%s,%s,%s,%s,%s) ;"
    print(SQLInsert)
    for follows in limit_handled(tweepy.Cursor(TwitterAPI.followers,id=SocialHandle).items()):
        today = date.today()
        try:
            if not follows.url:
                expandedURL =""
            else:
                #print(follows.url)
                expandedURL = follows.entities["url"]["urls"][0]["expanded_url"]
            #print(follows.screen_name, AboutMe.followers_count,AboutMe.friends_count,"from ", follows.location,"with ", " followers "," and provided this expanded URL: ",expandedURL )
            CrawlDate = today.strftime("%Y-%m-%d")
            #Insert into table
            SQLValues =(AboutMe.screen_name,AboutMe.followers_count,AboutMe.friends_count,"isFollowedBy",follows.screen_name,follows.followers_count,follows.location,expandedURL,CrawlDate)
            DBCursor.execute(SQLInsert,SQLValues)
            DBConnection.commit()
            print(AboutMe.screen_name,follows.screen_name,follows.followers_count)
        except StopIteration:
            DBConnection.close()
            break
        except:
            print(e.reason)
            DBConnection.close()
            break



---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-2-d095a0b00b72> in limit_handled(cursor)
      3         try:
----> 4             yield cursor.next()
      5         except tweepy.RateLimitError:

C:\Path\site-packages\tweepy\cursor.py in next(self)
    194             # Reached end of current page, get the next page...
--> 195             self.current_page = self.page_iterator.next()
    196             self.page_index = -1

C:\Path\site-packages\tweepy\cursor.py in next(self)
     69         if self.next_cursor == 0 or (self.limit and self.num_tweets == self.limit):
---> 70             raise StopIteration
     71         data, cursors = self.method(cursor=self.next_cursor,



【问题讨论】:

  • StopIteration 异常被触发时你想做什么?你想停止for循环吗?附带说明一下,在第二个异常捕获中,您需要编写 except Exception as e: 否则 eprint (e.reason) 中不存在,在任何情况下都必须替换为 print(str(e))
  • 我希望函数优雅地结束,这样一旦函数返回,我的代码就可以继续执行。我想它提交任何未完成的数据,关闭数据库连接,退出 for 循环,退出函数。这只是缺少“退货”声明的情况吗?我不明白的是,如果我有 StopIteration 异常,为什么在触发异常时我的函数仍然会导致 python 停止
  • 我去了docs.tweepy.org/en/v3.8.0/code_snippet.html,看到了limit_handled的实现。假设这就是您正在使用的,我不明白为什么您甚至会在您的代码中得到一个 StopIteration 异常(或者至少是 for follows in 语句不会自动处理的异常)。添加import traceback 语句并在您的StopIteration 异常处理程序中添加print(traceback.format_exc()) 以输出堆栈跟踪。
  • 我正在使用 tweepy 的 limit_handling。我已经添加了它和堆栈跟踪。看起来实际上是 limit_handling 引发了错误,那么解决方案是将 StopIteration 处理添加到限制函数吗?

标签: python-3.x error-handling tweepy stopiteration


【解决方案1】:

问题是 limit_handling 函数没有尝试捕获它抛出的 StopIteration 错误。下面改进的功能对我有用。感谢@Booboo 的帮助

def limit_handled(cursor):
    while True:
        try:
            yield cursor.next()
        except StopIteration:
            return
        except tweepy.RateLimitError:
            time.sleep(15 * 60)

【讨论】:

    猜你喜欢
    • 2015-07-26
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2015-01-03
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多