Jaron Bradley
Jaron Bradley

Reputation: 1119

Python Threads with Classes

I was going to post an example, but i said screw it and am just posting what i have instead. Go easy on me. I'm used to ruby. Python is brand new to me.

I have a file called que that holds a bunch of songs. i want to make a background thread that constantly checks to see if que has any songs in it. If it has songs in it then play the song on the first line, then remove the first line. (.que.swp).

Now the problem is, i don't know how to do this all in the background. I have another class that allows the user to add songs to the que file. So they need to be running at the same time.

class MusicPlayer(threading.Thread):

    def __init__(self):
        super(MusicPlayer, self).__init__()
        self.que_file = "que"
        self.playQue()

    def playQue(self):

        while 1:
            try:
                f = open(self.que_file, "r")
                songUp = f.readline()
                songUp = songUp.rstrip()
                cmd = "cvlc \"%s\" vlc://quit &>/dev/null" % (songUp)
                os.system(cmd)
                data="".join(open(self.que_file).readlines()[1:-1])
                open(".que.swp","wb").write(data)
                os.remove(self.que_file)
                os.rename(".que.swp", self.que_file)
                print "\n%s added %s to the que" % (self.user, self.dir)
            except:
                print "No Que File Exists"
                time.sleep(1)

#main#          
if __name__ == '__main__':
    player = MusicPlayer()
    player.start()
    print "helloWorld"

"helloworld" never prints to the terminal. it just keeps looping my class. ps - if it makes you feel better you can clean up any of my ugly commands. Remember I'm new. I've been at this a few hours and have resorted to asking.

Upvotes: 1

Views: 383

Answers (1)

David Robinson
David Robinson

Reputation: 78650

The looping starts not at the player.start() line as you might be guessing, but at the line:

player = MusicPlayer()

This is because you call self.playQue() in __init__. If you remove that line, and change the name of the method playQue to run, the thread should run separately.

See the instructions for the threading package for a description of start and run:

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

Upvotes: 1

Related Questions