python从线程d返回数据

2024-05-29 03:14:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码可以得到.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。


Tags: 文件函数代码标题deffilenamemp3audio
3条回答

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

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

这个函数使线程中运行的任何函数都能轻松地处理其返回值或异常:

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.")

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

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]

相关问题 更多 >

    热门问题