【发布时间】: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 这并不理想。