如何穿线 Tweepy 流

How to Thread a Tweepy Stream

我正在制作一个程序,使用 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"])

这是一个您可以轻松适应的示例... 该代码将创建一个线程,该线程在后台更新计数器,而循环将不断打印计数器的值。 'stop' 变量负责在主进程被杀死或退出时退出线程...

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

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

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

有关详细信息,请参阅 http://docs.tweepy.org/en/v3.5.0/streaming_how_to.html