2016-08-30 53 views
1

我正在製作一個程序,它使用Tweepy提取實時推文,並通過函數運行它。我正在使用Tweepy Stream來完成獲取推文的任務。不過,我希望在功能運行時,Tweepy仍然可以提取這些實時推文。我相信我需要線程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"]) 

回答

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