将 tweepy 流限制为特定数字 [英] Limit tweepy stream to a specific number
问题描述
class listener(StreamListener):
def on_status(self, status):
try:
userid = status.user.id_str
geo = str(status.coordinates)
if geo != "None":
print(userid + ',' + geo)
else:
print("No coordinates")
return True
except BaseException as e:
print('failed on_status,',str(e))
time.sleep(5)
def on_error(self, status):
print(status)
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(locations=[-97.54,32.55,-97.03,33.04])
我的 tweepy 流有这个脚本,它运行良好.但是,它会一直运行,直到我使用 'ctrl+c' 终止它.我尝试向on_status"添加一个计数器,但它没有增加:
I have this script for my tweepy stream, and it works perfectly. However, it keeps going until I terminate it using 'ctrl+c'. I tried adding a counter to "on_status" but it does not increment:
class listener(StreamListener):
def on_status(self, status):
i = 0
while i < 10:
userid = status.user.id_str
geo = str(status.coordinates)
if geo != "None":
print(userid + ',' + geo)
i += 1
无论我把增量放在哪里,它都会重复.如果我在课程前添加i=0",我会收到一个错误:
No matter where I put the increment, it repeats itself. If I add "i=0" before the class I get an error:
RuntimeError: No active exception to reraise
知道如何让计数器与流媒体一起工作吗?tweepy 附带的 Cursor 不适用于流式传输,至少据我所知.
Any idea how I can make the counter to work with streaming? The Cursor that comes with tweepy does not work with streaming, as far as I know at least.
推荐答案
您的 while 逻辑无法正常工作,因为 Tweepy
每次收到时都会在内部调用 on_status()
方法数据.因此,您无法通过在已经运行的无限循环中引入条件来控制流程,最好的方法是在类中创建一个新变量,该变量在创建 listener
对象时被实例化.并在 on_data()
方法中增加该变量.
Your while logic is not working properly because Tweepy
internally calls the on_status()
method whenever it receives data. So you can't control the flow of by introducing a conditional inside an already running infinite loop, The best way is to create a new variable inside the class, which gets instantiated when the listener
object is created. And increment that variable inside the on_data()
method.
class listener(StreamListener):
def __init__(self):
super().__init__()
self.counter = 0
self.limit = 10
def on_status(self, status):
try:
userid = status.user.id_str
geo = str(status.coordinates)
if geo != "None":
print(userid + ',' + geo)
else:
print("No coordinates")
self.counter += 1
if self.counter < self.limit:
return True
else:
twitterStream.disconnect()
except BaseException as e:
print('failed on_status,',str(e))
time.sleep(5)
这篇关于将 tweepy 流限制为特定数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!