我正在写一个简短的程序,我想异步调用一个函数,这样它就不会阻塞调用者.为此,我正在使用Pool
python的multiprocessing
模块.
在异步调用的函数中,我想返回一个namedtuple
以适应我程序其余部分的逻辑,但我发现a namedtuple
似乎不是从生成的进程传递给回调的受支持类型(可能是因为它不能被腌制).这是问题的最低限度.
from multiprocessing import Pool from collections import namedtuple logEntry = namedtuple("LogEntry", ['logLev', 'msg']) def doSomething(x): # Do actual work here logCode = 1 statusStr = "Message Here" return logEntry(logLev=logCode, msg=statusStr) def callbackFunc(result): print(result.logLev) print(result.msg) def userAsyncCall(): pool = Pool() pool.apply_async(doSomething, [1,2], callback=callbackFunc) if __name__ == "__main__": userAsyncCall() # Nothing is printed # If this is uncommented, the logLev and status are printed as expected: # y = logEntry(logLev=2, msg="Hello World") # callbackFunc(y)
有谁知道是否有办法namedtuple
将异步进程的返回值传递给回调?对于我正在做的事情,是否有更好/更多的pythonic方法?