简体   繁体   中英

Python multiprocessing: forwarding kwargs to actor function

Note: Python Multiprocessing - How to pass kwargs to function? does not answer this question.

procs.append(Process(target=fn, args=(cmd, results), kwargs=**kwargs))

Pycharm shows syntax error expression expected at ** for kwargs=**kwargs .

How should I pass the kwargs in without expanding?

I tried to use kwargs=kwargs as following

import multiprocessing
from multiprocessing import Process
import time


c = 0
def fn(a, res, **kwargs):
    print('sleeping: {}'.format(kwargs))
    time.sleep(10)
    global c
    c+=1
    res[a]=c
    print(res)

def test(**kwargs):
    cmds = ['1','2','3']
    procs = []
    manager = multiprocessing.Manager()
    results = manager.dict()
    for cmd in cmds:
        procs.append(Process(target=fn, args=(cmd, results), kwargs=kwargs))
        procs[-1].start()
    for proc in procs:
        proc.join()
    print(results)

if __name__ == '__main__':
    test(a=1, b=2)

But got the error:

self._target(*self._args, **self._kwargs)
TypeError: fn() got multiple values for argument 'a'
Process Process-3:

You have a variable name a in kwargs therefore the a parameter in function fn is defined in both cmd in kwargs . Try changing the param a in def fn(a, res, **kwargs): to another name or change a in test(a=1, b=2) to something like test(e=1, b=2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM