![](/img/trans.png)
[英]Live Stream Tweets from Twitter using Tweepy. But With NO Filter
[英]Tweepy. Make stream run forever
我對 tweepy python 庫比較陌生。 我想確保我的流 python 腳本始終在遠程服務器上運行。 因此,如果有人能分享如何實現它的最佳實踐,那就太好了。
現在我是這樣做的:
if __name__ == '__main__':
while True:
try:
# create instance of the tweepy tweet stream listener
listener = TweetStreamListener()
# set twitter keys/tokens
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
# create instance of the tweepy stream
stream = Stream(auth, listener)
stream.userstream()
except Exception as e:
print "Error. Restarting Stream.... Error: "
print e.__doc__
print e.message
time.sleep(5)
我對每個方法都返回False
: on_error(), on_disconnect(), on_timeout()
。 因此,通過返回False
流停止,然后在無限循環中重新連接。
這是我的工作方式,它已經運行了將近一年,在兩台計算機上處理導致流停止的錯誤。
#They don't need to be in the loop.
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
while True:
listener = TweetStreamListener()
stream = Stream(auth, listener, timeout=60)
try:
stream.userstream()
except Exception, e:
print "Error. Restarting Stream.... Error: "
print e.__doc__
print e.message
為了確保它永遠運行,您應該重新定義on_error
方法來處理重新連接嘗試之間的時間。 你的 5 秒睡眠會阻礙你成功重新連接的機會,因為 Twitter 會看到你嘗試這樣做過於頻繁。 但這是另一個問題。
只有我的兩分錢。
我收到了很多錯誤 420,這很奇怪,因為我沒有向流 API 要求太多關鍵字。
所以我發現流監聽器類的on_data()
方法必須總是返回True
。
我的有時返回False
,所以 tweepy 切斷了連接,並直接在循環中重新創建它,twitter 不太喜歡它......
我還通過在異常上遞歸創建新流來解決這個問題。
這是我的完整代碼。 只需更改mytrack
變量,放置您的密鑰並使用pm2
或python
運行它。
from tweepy import OAuthHandler, Stream, StreamListener
import json
mytrack = ['netmine', 'bitkhar', 'bitcoin']
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
class StdOutListener(StreamListener):
def __init__(self, listener, track_list, repeat_times):
self.repeat_times = repeat_times
self.track_list = track_list
print('************** initialized : #', self.repeat_times)
def on_data(self, data):
print(self.repeat_times, 'tweet id : ', json.loads(data)['id'])
def on_exception(self, exception):
print('exception', exception)
new_stream(auth, self.track_list, self.repeat_times+1)
def on_error(self, status):
print('err', status)
if status == 420:
# returning False in on_data disconnects the stream
return False
def new_stream(auth, track_list, repeat_times):
listener = StdOutListener(StreamListener, track_list, repeat_times)
stream = Stream(auth, listener).filter(track=track_list, is_async=True)
new_stream(auth, mytrack, repeat_times=0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.