2016-05-13 36 views
0

流,我成功地使用下面的代碼,聽取他們對帳戶的直接消息流:的Python Tweepy使用Python 2.7的多任務處理

from tweepy import Stream 
from tweepy import OAuthHandler 
from tweepy import API 
from tweepy.streaming import StreamListener 

# These values are appropriately filled in the code 

consumer_key = '######' 
consumer_secret = '######' 
access_token = '######' 
access_token_secret = '######' 

class StdOutListener(StreamListener): 

    def __init__(self): 
     self.tweetCount = 0 

    def on_connect(self): 
     print("Connection established!!") 

    def on_disconnect(self, notice): 
     print("Connection lost!! : ", notice) 

    def on_data(self, status): 
     print("Entered on_data()") 
     print(status, flush = True) 
     return True 
     # I can add code here to execute when a message is received, such as slicing the message and activating something else 

    def on_direct_message(self, status): 
     print("Entered on_direct_message()") 
     try: 
      print(status, flush = True) 
      return True 
     except BaseException as e: 
      print("Failed on_direct_message()", str(e)) 

    def on_error(self, status): 
     print(status) 

def main(): 

    try: 
     auth = OAuthHandler(consumer_key, consumer_secret) 
     auth.secure = True 
     auth.set_access_token(access_token, access_token_secret) 

     api = API(auth) 

     # If the authentication was successful, you should 
     # see the name of the account print out 
     print(api.me().name) 

     stream = Stream(auth, StdOutListener()) 

     stream.userstream() 

    except BaseException as e: 
     print("Error in main()", e) 

if __name__ == '__main__': 
    main() 

這是偉大的,當我收到我還可以執行代碼一條消息,但是我添加到工作隊列中的工作需要能夠在一段時間後停止。我使用一個流行的start = time.time()並減去當前時間來確定流逝的時間,但是這個流式代碼不會循環來檢查時間。我只是在等待一個新的消息,所以時鐘從不檢查這麼說。

我的問題是這樣的:我怎樣才能讓流發生,並仍然追蹤時間流逝?我是否需要使用本文中描述的多線程? http://www.tutorialspoint.com/python/python_multithreading.htm

我是新來的Python和玩附近的樹莓派硬件樂趣。我已經從Stackoverflow學到了很多東西,謝謝大家:)

回答

0

我不確定你要如何決定什麼時候停止,但你可以通過timeout argument到流中放棄一定的延遲。

stream = Stream(auth, StdOutListener(), timeout=30) 

這會調用您的聽衆的on_timeout() method。如果你返回true,它將繼續流式傳輸。否則,它將停止。

在流的超時參數和您的監聽器on_timeout()之間,您應該能夠決定何時停止流式傳輸。

+0

我喜歡你的想法,我想我會把它放在我的後面的口袋裏,並嘗試這個多線程的東西。我認爲,如果我可以將流分成單個函數(我認爲它將是main()),並且它可以更新全局變量,然後可以由其他線程訪問,但我可能會很樂意去。 – sakko303

0

我發現我能夠以我想要的方式獲得一些多線程代碼。我給出了一個例子,用不同的定時參數啓動相同代碼的多個實例,我可以得到兩個不同的代碼塊,以在它們自己的實例中運行。

一個代碼塊不斷向全局變量中添加10 VAR)。 另一個塊會在5秒鐘後檢查,然後打印var的值。

這演示了使用Python多線程執行和共享數據的2個不同任務。

見下面的代碼

import threading 
import time 

exitFlag = 0 
var = 10 

class myThread1 (threading.Thread): 
    def __init__(self, threadID, name, counter): 
     threading.Thread.__init__(self) 
     self.threadID = threadID 
     self.name = name 
     self.counter = counter 
    def run(self): 
     #var counting block begins here 
     print "addemup starting" 
     global var 
     while (var < 100000): 
      if var > 90000: 
       var = 0 
      var = var + 10 



class myThread2 (threading.Thread): 
    def __init__(self, threadID, name, counter): 
     threading.Thread.__init__(self) 
     self.threadID = threadID 
     self.name = name 
     self.counter = counter 
    def run(self): 
     #time checking block begins here and prints var every 5 secs 
     print "checkem starting" 
     global var 
     start = time.time() 
     elapsed = time.time() - start 
     while (elapsed < 10): 
      elapsed = time.time() - start 
      if elapsed > 5: 
       print "var = ", var 
       start = time.time() 
       elapsed = time.time() - start 

# Create new threads 
thread1 = myThread1(1, "Thread-1", 1) 
thread2 = myThread2(2, "Thread-2", 2) 

# Start new Threads 
thread1.start() 
thread2.start() 

print "Exiting Main Thread" 

我的下一個任務將是打破我的Twitter流在其自己的線程,並通過作爲變量排隊程序的任務直接接到消息,而希望第一個線程繼續聽更直接的信息。

+0

您鏈接的教程太可怕了。最後提供使用Python的Queue,並在其上添加同步機制。我錯過了什麼嗎?爲什麼這需要?此外,它稱之爲「優先隊列」 - 它不是(再次,據我所知 - 我錯過了什麼?) – guyarad