我正在製作一個簡單的應用程序來流式傳輸twitter的公共時間表,並且我希望流式傳輸在一小時後自動停止,並且我不知道如何執行此操作。我閱讀日期時間和timeit文檔,但無法理解它們。這裏是我的代碼,它正在流暢地完成我想要的時間線,但無限期地。如何在Python中使用1小時後退出函數
from twython import TwythonStreamer
import json
import os
import datetime
from datetime import *
APP_KEY = 'XX'
APP_SECRET = 'XX'
OAUTH_TOKEN = 'XX'
OAUTH_TOKEN_SECRET = 'XX'
class MyStreamer(TwythonStreamer):
def on_success(self, data):
print data['text']
with open('scratch1.json', 'ab') as outfile:
json.dump(data, outfile, indent = 4)
with open('scratch2.json', 'ab') as xoutfile:
json.dump(data, xoutfile, indent = 4)
return
def on_error(self, status_code, data):
print status_code
return True # Don't kill the stream
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream
stream = MyStreamer(APP_KEY, APP_SECRET,
OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.filter(follow = [95995660, 8820362])
任何人都可以幫我嗎?
謝謝,完美的作品。 –
我無法獲取此代碼進行復制。我收到錯誤消息「TypeError:__init __()需要1個位置參數,但給出了5個」。不再有流。狀態選項,但有一個用於stream.on_success。如果我添加app_key,app_secret,oauth_token和oauth_token_secret,我就失去了使用stream.statuses的能力。 – ZacharyST
看起來自上游'twython'圖書館自從2014年1月初以來已經發生變化:https://github.com/ryanmcgrath/twython/blob/master/twython/streaming/api.py#L22 – pztrick