ccwhite1 ccwhite1 - 2 months ago 4
Python Question

python Returning data from a threaded def

I have a bit of code that gets the title of a .MP3 file

def getTitle(fileName):
print "getTitle"
audio = MP3(fileName)

sTitle = str(audio["TIT2"])
except KeyError:
sTitle = os.path.basename(fileName)

sTitle = replace_all(sTitle) #remove special chars

return sTitle

I would call this function with

sTitle = getTitle("SomeSong.mp3")

To solve another problem I wanted to spawn this on its own thread so I altered my call to

threadTitle = Thread(target=getTitle("SomeSong.mp3"))

This correctly calls the function and solves my other problem, but now I can't figure out how to get the return value of sTitle from the function into Main.


I would make a new object that extends thread so that you can get anything you want out of it at any time.

from threading import Thread

class GetTitleThread(Thread):        

    def __init__(self, fileName):
        self.sTitle = None
        self.fileName = fileName
        super(GetTitleThread, self).__init__()

    def run(self):
        print "getTitle"
        audio = MP3(self.fileName)

            self.sTitle = str(audio["TIT2"])
        except KeyError:
            self.sTitle = os.path.basename(self.fileName)

        self.sTitle = replace_all(self.sTitle) #remove special chars

if __name__ == '__main__':
    t = GetTitleThread('SomeSong.mp3')
    print t.sTitle