KeepRunning /重新启动python脚本(TwitterAPI)

时间:2017-03-16 16:17:42

标签: python twitter

您好Stackoverflow社区,

我有一个关于让Python继续运行来自Twitter Streaming API的流数据的问题。

以下是我使用的Twitter Streaming API的基本版本

#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

#Variables that contains the user credentials to access Twitter API 
access_token = "<>"
access_token_secret = "<>"
consumer_key = "<>"
consumer_secret = "<>"

##########################################################
# listener received tweets to stdout - MINUTE
class StdOutListener(StreamListener):

    def on_data(self, data):
        print(data)
        return True

    def on_error(self, status):
        print(status)

##########################################################
# Main program
if __name__ == '__main__':

    #This handles Twitter authetification and the connection to Twitter Streaming API
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    # Initiate the connection to Streaming API
    twitter_stream = Stream(auth, l)

    # Get a sample of the public data following through Twitter
    twitter_stream.sample()

有时,流媒体停止工作(由于Twitter重启API或文件系统,我不确定),错误如下图所示

StreamAPIError1

StreamAPIError2

我的问题是我们是否有任何技术可以保持python文件的运行:
- 像构建测试文件1是否正在运行的第二个文件一样,每次文件1失败时激活文件1 - 或者在文件1中集成一些技术,使其重新启动 - 或者更多的建议。

我可以得到你的意见吗?如果代码

,那就好多了

谢谢。

1 个答案:

答案 0 :(得分:1)

我已经使用retrying库对python Twitter机器人产生了良好的效果。

https://pypi.python.org/pypi/retrying

有代码示例,但它就像在函数上使用@retry装饰器一样简单。 编辑: 您可以在课程的方法中使用它:

@retry
def on_data():
    <code>

NB twitter会记录您对其API进行的调用次数,因此您必须小心,不要使用它。

编辑: 根据我的经验,如果你需要从阻止你的人那里得到推文,这不会有帮助,因为它会一直失败,所以你需要投入一些东西来解决这个问题。

相关问题