【问题标题】:KeepRunning/Restarting a python script (TwitterAPI)KeepRunning/重新启动 python 脚本 (TwitterAPI)
【发布时间】:2017-03-17 01:51:33
【问题描述】:

你好 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 或文件系统,我不确定),错误如下图所示

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

我能听听你的意见吗?如果有代码就更好了

谢谢。

【问题讨论】:

  • 在所有内容周围添加try...except BaseException 块?
  • 我在回答中找到解决方案时尝试了这个。 Iirc 它不起作用,因为您必须让它重试,所以我最终在一段时间内将它包装起来 True 这并不理想。

标签: python twitter


【解决方案1】:

我已经使用 retrying 库在 python Twitter 机器人上取得了良好的效果。

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

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

@retry
def on_data():
    <code>

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

编辑: 根据我的经验,如果您需要从阻止您的人那里获取推文,这将无济于事,因为它会一直失败,因此您需要采取一些措施来解决这个问题。

【讨论】:

  • 感谢您的贡献。在这种情况下,我应该将命令放在类上方,例如 .
    @retry
    class StdOutListener(StreamListener): ?
猜你喜欢
  • 2020-09-13
  • 2010-12-17
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2014-05-06
  • 1970-01-01
相关资源
最近更新 更多