如何线索Tweepy Stream

时间:2016-08-30 21:33:20

标签: python multithreading python-3.x twitter tweepy

我正在制作一个使用Tweepy提取实时推文的程序,并通过一个函数运行它。我正在使用Tweepy Stream来完成获取推文的任务。但是,我希望在功能运行时,Tweepy仍然可以提取这些实时推文。我相信我需要线程化Tweepy事件监听器,但我不完全确定如何做到这一点。

def doesSomething(s):
    #function here

class listener(tweepy.StreamListener):
    def on_status(self, status):
        doesSomething(status)

stream_listener = listener()
tweepy.Stream(auth = api.auth, listener=stream_listener)
stream.filter(track=["Example"])

2 个答案:

答案 0 :(得分:1)

这是一个你可以轻松适应的例子...... 代码将创建一个线程,在后台更新计数器,而循环将连续打印计数器的值。 '停止'当主进程被终止或退出时,变量负责退出线程...

import threading
import time
from sys import stdout

# Only data wihtin a class are actually shared by the threads
class Counter(object):
    counter = 0
    stop = False

# Function that will be executed in parallel with the rest of the code
def function_1():
    for i in range(10):
        if c.stop: return # With more will exit faster
        time.sleep(2)
        c.counter += 1
        if c.stop: return

# Create a class instance
c = Counter()

# Thread function_1
d = threading.Thread(target=function_1)
d.start()

# Exit the thread properly before exiting...
try:
    for j in range(100):
        stdout.write('\r{:}'.format(c.counter))
        stdout.flush()
        time.sleep(1)
except:
    c.stop = True

答案 1 :(得分:1)

您可以使用async = True参数在另一个线程中运行流:

myStream.filter(track=['python'], async=True)

有关更多信息,请参见http://docs.tweepy.org/en/v3.5.0/streaming_how_to.html