保持运行/重启 python 脚本 (TwitterAPI) [英] KeepRunning/Restarting a python script (TwitterAPI)
问题描述
你好 Stackoverflow 社区,
Hi Stackoverflow community,
我有一个关于保持 Python 继续运行以从 Twitter Streaming API 流式传输数据的问题.
I have a question about keeping the Python keep running to streaming data from Twitter Streaming API.
以下是我使用的 Twitter Streaming API 的基本版本
Below is the basic version of the Twitter Streaming API I used
#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 或文件系统,我不确定),错误如下图所示
Sometimes, the streaming stop working (due to Twitter restart API, or file system, I am not sure), the error is like in the pictures below
我的问题是我们是否有任何技术来保持 python 文件运行:
- 就像构建第二个文件来测试文件 1 是否正在运行,然后在每次文件 1 失败时激活文件 1
- 或者在文件 1 中集成一些技术使其重新启动
- 或者更多的建议.
My question is that do we have any technique to keep a python file running:
- Like building a second file that test if file 1 is running, then activate file 1 everytime file 1 fails
- Or integrate some techniques in file 1 to make it restart itself
- Or some more suggestion.
我能听听你的意见吗?要是有代码就好多了
Can I have your opinion. It is a lot better if it comes the code
谢谢.
推荐答案
我已经将 retrying
库用于 Python Twitter 机器人,效果很好.
I've used the retrying
library to good effect with python Twitter bots.
https://pypi.python.org/pypi/retrying
有代码示例,但它几乎就像在您的函数上使用 @retry
装饰器一样简单.您可以在类的方法中使用它:
Has code examples, but it's pretty much as simple as using a @retry
decorator on your function.
You could use it on the methods for your class:
@retry
def on_data():
<code>
NB twitter 会记录您对其 API 的调用次数,因此您必须小心不要用完它.
NB twitter logs how many calls you make to its API so you have to be careful that this doesn't use it up.
根据我的经验,如果你需要从阻止你的人那里得到一条推文,这无济于事,因为它会一直失败,所以你需要采取一些措施来解决这个问题.
From my experiences, if you need to get a tweet from someone who has blocked you, this won't help because it will keep failing, so you'll need to put something in to deal with this.
这篇关于保持运行/重启 python 脚本 (TwitterAPI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!