我正在制作一个简单的应用程序来流式传输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