Python 将变量传递给多处理池

时间:2021-01-05 08:30:43

标签: python variables multiprocessing global 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

1 个答案:

答案 0 :(得分:2)

您可以将变量与 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 中。

相关问题