从线程def返回数据

ccw*_*te1 7 python multithreading

我有一些代码可以获得.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
Run Code Online (Sandbox Code Playgroud)

我会用这个函数调用

sTitle = getTitle("SomeSong.mp3")
Run Code Online (Sandbox Code Playgroud)

为了解决另一个问题,我想在自己的线程上生成它,所以我改变了我的调用

threadTitle = Thread(target=getTitle("SomeSong.mp3"))
threadTitle.start()
Run Code Online (Sandbox Code Playgroud)

这正确地调用了函数并解决了我的其他问题,但现在我无法弄清楚如何将sTitle的返回值从函数转换为Main.

Iac*_*cks 19

我会创建一个扩展线程的新对象,以便随时可以从中获取任何内容.

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
Run Code Online (Sandbox Code Playgroud)


Sve*_*ach 15

一种方法是使用存储结果的包装器:

def wrapper(func, args, res):
    res.append(func(*args))

res = []
t = threading.Thread(
    target=wrapper, args=(getTitle, ("SomeSong.mp3",), res))
t.start()
t.join()
print res[0]
Run Code Online (Sandbox Code Playgroud)