gpt4 book ai didi

python - 保持运行/重新启动 python 脚本 (TwitterAPI)

转载 作者:太空宇宙 更新时间:2023-11-03 15:32:02 25 4
gpt4 key购买 nike

您好,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中集成一些技术,使其自行重启
- 或者更多建议。

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

谢谢。

最佳答案

我在 Python Twitter 机器人中使用了 retrying 库,效果良好。

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

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

@retry
def on_data():
<code>

注意 Twitter 会记录您对其 API 的调用次数,因此您必须小心,以免耗尽它。

编辑:根据我的经验,如果您需要从屏蔽您的人那里获取一条推文,这不会有帮助,因为它会不断失败,因此您需要添加一些东西来处理这个问题。

关于python - 保持运行/重新启动 python 脚本 (TwitterAPI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42839474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com