2017-02-23 70 views
0

我創建了一個程序,它可以通過twitter進行流式處理,並根據使用pygame庫播放音樂的tweets生成的結果。以下是我的代碼示例。在Python中對多個函數進行線程化處理

class listener(StreamListener): 

def on_status(self, status): 
    global mood_happy, mood_sad, mood_angry, mood_shocked, mood_romantic 

    try: 
     # print status 
     tweet_text = status.text 
     for mood_n_score in [[happy, 'mood_happy'], [sad, 'mood_sad'], [angry, 'mood_angry'], 
          [shocked, 'mood_shocked'], [romantic, 'mood_romantic']]: 
      lst_mood = mood_n_score[0] 
      type_mood = mood_n_score[1] 

      for mood in lst_mood: 
       if mood in tweet_text: 
        if type_mood == 'mood_happy': 
         mood_happy += 1 
        elif type_mood == 'mood_sad': 
         mood_sad += 1 
        elif type_mood == 'mood_angry': 
         mood_angry += 1 
        elif type_mood == 'mood_shocked': 
         mood_shocked += 1 
        else: 
         mood_romantic += 1 
        break 

     print('\n----------------') 
     print 'mood_happy:', mood_happy 
     print 'mood_sad:', mood_sad 
     print 'mood_angry:', mood_angry 
     print 'mood_shocked:', mood_shocked 
     print 'mood_romantic:', mood_romantic 



     top_mood=max(mood_happy,mood_sad,mood_angry,mood_shocked,mood_romantic) 
     if top_mood==mood_happy: 
      print "the mood is: happy" 
      pygame.mixer.music.load(file.mp3) 
      pygame.mixer.music.play() 

正如你所看到的,我有一個流式類,它不斷地通過twitter流動並打印出最高的心情。當我運行我的代碼播放mp3文件時,流式傳輸將停止,只有音樂播放。我怎樣才能讓我的節目流通過Twitter並同時播放音樂?

謝謝!

回答

0

我從來沒有使用pygame,但基於它的作用,我想我可以假設它不是線程安全的。

我會做的是在線程中使用threading模塊的流媒體代碼,並讓音樂播放邏輯始終等待主線程設置threading.Event

import threading 
import pygame 


new_mood_event = threading.Event() 


class TwitterStreamer(StreamListener): 
    def run(self): 
     while True: # keep the streamer going forever 
      pass # define your code here 

    def on_status(self, status): 
     # ... Define your code here 
     if top_mood == mood_happy: 
      new_mood_event.mp3_file_path = 'happy_file.mp3' 
      new_mood_event.set() # alert the main thread we have a new mood to play 


if __name__ == '__main__': 
    twitter_streamer = TwitterStreamer() 
    streaming_thread = threading.Thread(target=twitter_streamer.run) # creates a thread that will call `twitter_streamer.run()` when executed 
    streaming_thread.start() # starts the thread 

    # everything from here will be run in the main thread 
    while True: # creates an "event loop" 
     new_mood_event.wait() # blocks the main thread until `new_mood_event.set()` is called by `on_status` 
     new_mood_event.clear() # clears the event. if we don't clear the event, then `new_mood_event.wait()` will only block once 
     pygame.mixer.music.load(new_mood_event.mp3_file_path) 
     pygame.mixer.music.play() 
+0

嘿,感謝您的回答! :)請你向我解釋一下代碼的最後兩部分究竟在做什麼? –

+0

哪部分?我在哪裏創建'streaming_thread','new_mood_event.wait()'然後'new_mood_event.clear()',或修改的pygame代碼? – Terrence

+0

從__name___ == __'main'__:到最後一行。我不太瞭解線程,因此這對我來說似乎是陌生的。 :p –