我正在嘗試使用Stream.filter()方法將twitter數據流式傳輸5分鐘。我將檢索到的推文存儲在JSON文件中。問題是我無法停止程序內的filter()方法。我需要手動停止執行。我嘗試使用時間包基於系統時間停止數據。我能夠停止向JSON文件發送推文,但流方法仍在繼續,但無法繼續執行下一行代碼。 我正在使用IPython筆記本來編寫和執行代碼。 下面的代碼:無法在一分鐘後停止流式傳輸
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
from tweepy import Stream
from tweepy.streaming import StreamListener
class MyListener(StreamListener):
def __init__(self, start_time, time_limit=60):
self.time = start_time
self.limit = time_limit
def on_data(self, data):
while (time.time() - self.time) < self.limit:
try:
saveFile = open('abcd.json', 'a')
saveFile.write(data)
saveFile.write('\n')
saveFile.close()
return True
except BaseException as e:
print 'failed ondata,', str(e)
time.sleep(5)
return True
def on_status(self, status):
if (time.time() - self.time) >= self.limit:
print 'time is over'
return false
def on_error(self, status):
if (time.time() - self.time) >= self.limit:
print 'time is over'
return false
else:
print(status)
return True
start_time = time.time()
stream_data = Stream(auth, MyListener(start_time,20))
stream_data.filter(track=['name1','name2',...list ...,'name n'])#list of the strings I want to track
這些鏈接是相似的,但我並沒有回答我的問題直接
Tweepy: Stream data for X minutes?
Stopping Tweepy steam after a duration parameter (# lines, seconds, #Tweets, etc)
Tweepy Streaming - Stop collecting tweets at x amount
我用這個鏈接是我參考, http://stats.seandolinar.com/collecting-twitter-data-using-a-python-stream-listener/
您有一個有效的問題,無需擔心。你是什麼意思*問題是我無法停止程序中的filter()方法。*你是否試圖暫停流?或者更改過濾器關鍵字? – Leb
@Leb我希望當我需要它運行時,流在一小時內說一次。如果我讓它永遠運行,它只會達到API限制並停止工作。我想在代碼中以編程方式打開和關閉流。 – Abin