从线程def返回数据

时间:2011-03-16 11:42:42

标签: 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

我会用

调用此函数
sTitle = getTitle("SomeSong.mp3")

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

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

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

3 个答案:

答案 0 :(得分:18)

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

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

答案 1 :(得分: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]

答案 2 :(得分:1)

这个可以让任何函数在一个线程中运行,以处理它的返回值或异常:

def threading_func(f):
    """Decorator for running a function in a thread and handling its return
    value or exception"""
    def start(*args, **kw):
        def run():
            try:
                th.ret = f(*args, **kw)
            except:
                th.exc = sys.exc_info()
        def get(timeout=None):
            th.join(timeout)
            if th.exc:
                raise th.exc[0], th.exc[1], th.exc[2] # py2
                ##raise th.exc[1] #py3                
            return th.ret
        th = threading.Thread(None, run)
        th.exc = None
        th.get = get
        th.start()
        return th
    return start

使用示例

def f(x):
    return 2.5 * x
th = threading_func(f)(4)
print("still running?:", th.is_alive())
print("result:", th.get(timeout=1.0))

@threading_func
def th_mul(a, b):
    return a * b
th = th_mul("text", 2.5)

try:
    print(th.get())
except TypeError:
    print("exception thrown ok.")