繁体   English   中英

Python 将变量传递给多处理池

[英]Python pass variable to multiprocessing pool

我多年来一直试图弄清楚这一点,但想知道是否有人知道我如何将s变量传递给池而不将其作为参数?

import ctypes
import multiprocessing as mp
import os

def worker1(n):
    k = n*3
    print(k)
    print(s)
    # print(ctypes_int.value)

if __name__ == '__main__':
    # global s
    somelist = [1,2,3]

    # ctypes_int = mp.Value(ctypes.c_wchar_p , "hi")
    s = "TESTING"
    # worker1(1)
    p = mp.Pool(1)
    p.map(worker1,somelist)

这是我得到的错误:

3
6
9
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Program Files\Python\Python37\lib\multiprocessing\pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "C:\Program Files\Python\Python37\lib\multiprocessing\pool.py", line 44, in mapstar
    return list(map(*args))
  File "C:\Users\light\AppData\Local\Temp\tempCodeRunnerFile.python", line 10, in worker1
    print(s)
NameError: name 's' is not defined
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\light\AppData\Local\Temp\tempCodeRunnerFile.python", line 21, in <module>
    p.map(worker1,somelist)
  File "C:\Program Files\Python\Python37\lib\multiprocessing\pool.py", line 268, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "C:\Program Files\Python\Python37\lib\multiprocessing\pool.py", line 657, in get
    raise self._value
NameError: name 's' is not defined

您可以将变量与somelist中的每个项目一起传递:

import multiprocessing as mp

def worker1(p):
    n,s = p
    k = n*3
    print(k)
    print(s)

if __name__ == '__main__':
    somelist = [1,2,3]

    s = "TESTING"
    p = mp.Pool(1)
    p.map(worker1,[(n,s) for n in somelist])

参数(n,s)作为p传递,我将其解压缩到n,s中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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