2017-02-23 78 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 –

相关问题