我有一些代码可以获取.MP3文件的标题

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

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

    sTitle = replace_all(sTitle) #remove special chars

    return sTitle

我会用这个功能
sTitle = getTitle("SomeSong.mp3")

为了解决另一个问题,我想在自己的线程上生成它,所以我更改了对
threadTitle = Thread(target=getTitle("SomeSong.mp3"))
threadTitle.start()

这可以正确调用该函数并解决了我的其他问题,但是现在我不知道如何将sTitle的返回值从函数获取到Main中。

最佳答案

我将创建一个扩展线程的新对象,以便您可以随时从中获得所需的任何东西。

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)

        try:
            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')
    t.start()
    t.join()
    print t.sTitle

10-01 17:41