简体   繁体   中英

Threading multiple functions in python

I've created a program that streams through twitter and based on the result of generated by the tweets it plays music using the pygame library. Below is a sample of my code.

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()

As you can see, I have a streamer class which streams through twitter continously and prints the top mood. When I run my code to play the mp3 file, the streaming stops and only the music plays. How can I make my program stream through twitter and play music at the same time?

Thank you!

I have never used pygame, but based on what it does I think I can probably assume it's not thread-safe.

What I would do is have the streaming code in a thread using the threading module and have the music playing logic constantly wait on the main thread for a threading.Event to be set.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM