特威皮.让流永远运行 [英] Tweepy. Make stream run forever

查看:22
本文介绍了特威皮.让流永远运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 tweepy python 库比较陌生.我想确保我的流 python 脚本始终在远程服务器上运行.因此,如果有人能分享如何实现这一目标的最佳实践,那就太好了.

I am relatively new to tweepy python library. I want to be sure that my stream python script always runs on a remote server. So it would be great if someone will share the best practices on how to make it happen.

现在我是这样做的:

if __name__ == '__main__':

while True:

    try:

        # create instance of the tweepy tweet stream listener
        listener = TweetStreamListener()

        # set twitter keys/tokens
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

        # create instance of the tweepy stream
        stream = Stream(auth, listener)

        stream.userstream()
    except Exception as e:
        print "Error. Restarting Stream.... Error: "
        print e.__doc__
        print e.message
        time.sleep(5)

我在每个方法上都返回 False:on_error()、on_disconnect()、on_timeout().因此,通过返回 False 流停止,然后在无限循环中重新连接.

And I return False on each of the methods: on_error(), on_disconnect(), on_timeout(). So, by returning False the stream stops and then reconnects in the infinite loop.

推荐答案

这是我的方法,它已经运行了将近一年,在两台计算机上处​​理导致流停止的错误.

Here's how I do mine and it's been running for almost a year, on two computers to handle the errors that stop the stream here and there.

#They don't need to be in the loop.
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

while True:
    listener = TweetStreamListener()
    stream = Stream(auth, listener, timeout=60)

    try:
        stream.userstream()

    except Exception, e:
        print "Error. Restarting Stream.... Error: "
        print e.__doc__
        print e.message

为了确保它永远运行,您应该重新定义 on_error 方法来处理重新连接尝试之间的时间.你 5 秒钟的睡眠会阻碍你成功重新连接的机会,因为 Twitter 会看到你尝试这样做过于频繁.但这是另一个问题.

To make sure that it runs forever, you should redefine the on_error method to handle the time between reconnection attempts. Your 5 seconds sleeping will hinder your chances to a successful reconnect because Twitter will see that you tried to do it too frequently. But that's another question.

这篇关于特威皮.让流永远运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆