如何在 python 多处理池 apply_async 中使用关键字参数

how do I use key word arguments with python multiprocessing pool apply_async(如何在 python 多处理池 apply_async 中使用关键字参数)
本文介绍了如何在 python 多处理池 apply_async 中使用关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试掌握 python 的多处理模块,特别是 Pool 的 apply_async 方法.我正在尝试使用参数和关键字参数调用函数.如果我在没有 kwargs 的情况下调用该函数,那很好,但是当我尝试添加关键字参数时,我得到:TypeError: apply_async() got an unexpected keyword argument 'arg2'下面是我正在运行的测试代码

I'm trying to get to grips with pythons multiprocessing module, specifically the apply_async method of Pool. I'm trying to call a function with arguments and keyword arguments. If I call the function without kwargs it's fine but when I try to add in a keyword argument I get: TypeError: apply_async() got an unexpected keyword argument 'arg2' Below is the test code that I'm running

#!/usr/bin/env python
import multiprocessing
from time import sleep
def test(arg1, arg2=1, arg3=2):
    sleep(5)

if __name__ == '__main__':
    pool = multiprocessing.Pool()
    for t in range(1000):
        pool.apply_async(test, t, arg2=5)
    pool.close()
    pool.join()

如何调用函数以使其接受关键字参数?

How can I call the function so that it accepts keyword arguments?

推荐答案

在字典中传递关键字 args(以及在元组中的位置参数):

Pass the keyword args in a dictionary (and the positional arguments in a tuple):

pool.apply_async(test, (t,), dict(arg2=5))

这篇关于如何在 python 多处理池 apply_async 中使用关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)