我正在写一个简短的程序,我想异步调用一个函数,这样它就不会阻塞调用者.为此,我正在使用Poolpython的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") …Run Code Online (Sandbox Code Playgroud) 我写了下面的代码,它应该检查列表中的数字是否是质数,但是有一个我无法解决的问题,因为我正在尝试实现对平方根的检查优化num,我有一个类型错误。
def is_prime(x):
if x <= 1:
return False
if x == 2:
return True
for n in range(3, x**(0.5)+1, 2): # this skips even numbers and only checks up to sqrt(x)
if x % n == 0:
return False
return True
my_list = [1,2,4,5,6,7]
result = list(map(is_prime,my_list))
print(result)
Run Code Online (Sandbox Code Playgroud)
File "PrimeCheck.py", line 39, in <module>
result = list(map(is_prime,my_list))
File "PrimeCheck.py", line 32, in is_prime
for n in range(3, x**(0.5)+1, 2): # this skips even numbers and only checks up to …Run Code Online (Sandbox Code Playgroud)