首页 > 解决方案 > 让我的 Tweepy 流停止时遇到问题

问题描述

一旦达到 100 条推文,就无法让我的流退出。我尝试了很多方法。希望保持“开放”的用法。

*在文件打开时使用 while 循环会导致杂乱无章的 JSON 文件 *当前使用的断开连接在达到 100 后会继续流式传输,但数据已损坏

编辑:

  1. 使用 self 重新创建了推文数量和推文总数。
  2. 每次加载数据时,都会更新 num_tweets:self.num_tweets+=1。然后更新pbar:self.pbar.update(1)
  3. 在 try 语句之外,如果 self.num_tweets < self.total_tweets,则返回 True,否则 self.pbar.close() 并返回 False

信用:克里斯库克曼

def __init__(self, api=None):
        self.num_tweets = 0
        self.total_tweets = int(input("Number of tweets:"))
        self.pbar = tqdm(total=self.total_tweets)
        self.unsaved = 0
        self.emojis = 0

    def on_data(self, data):
        try:
            portal_1 = creds()
            rawTweets = json.loads(data)
            self.num_tweets += 1
            self.pbar.update(1)
            ...
            ...
        except BaseException as e:
            print(colored("Error on_data: %s", "red") % str(e))
        if self.num_tweets < self.total_tweets:
            return True
        else:
            self.pbar.close()
            return False

标签: pythonsocket.iotweepy

解决方案


要使用 tweepy 退出流,您需要从 on_status 函数返回 false,因此如果您更改:

if self.num_tweets < 100:
    return True
    else:
        twitter_stream.disconnect()

至:

if self.num_tweets < 100:
    return True
else:
    self.pbar.close() # Closes the instance of the progress bar.
    return False # Closes the stream.

那应该解决它。顺便说一句,每次运行时添加 self.num_tweets 以获取进度条:

self.pbar.update(self.num_tweets)

通过更新,您每次都添加推文数量:

推文 1 | 推文数 = 的 1 | 进度条 = 的 1 (1)

推文 2 | 推文数 = 的 2 | 进度条 = 的 1 + 2 (3)

推文 3 | 推文数 = 的 3 | 进度条 = 的 3 + 3 (6)

从您的代码中,我假设您的意图是增加它们,所以要做到这一点,您只需将其更改为:

self.pbar.update(1)

希望这可以帮助。


推荐阅读