【问题标题】:Python multiprocess library: NameError on using imported packagesPython 多进程库:使用导入包时出现 NameError
【发布时间】:2019-05-01 11:37:13
【问题描述】:

以下代码完美运行:

from multiprocessing import Pool
import time

values = list(range(10))

def print_time_and_value(value):
    print(time.time(), value)

if __name__ == '__main__':

    p = Pool(4)
    p.map(print_time_and_value, values)

但是当我将“多处理”导入更改为"multiprocess" 库时:

from multiprocess import Pool

它在执行过程中引发以下错误:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    p.map(print_time_and_value, values)
  File "C:\Users\User\Anaconda3_64bits\lib\site-packages\multiprocess\pool.py", line 268, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "C:\Users\User\Anaconda3_64bits\lib\site-packages\multiprocess\pool.py", line 657, in get
    raise self._value
NameError: name 'time' is not defined

我不能使用多进程,因为稍后我必须在我的主应用程序上使用不可提取的对象,所以我必须使用具有 dill 序列化的多进程。

我注意到将“时间”导入放在“print_time_and_value”函数而不是全局范围内可以解决这个问题,但是这种行为有点奇怪。由于它是多处理的一个分支,我猜想它会以同样的方式工作。

我使用的是 Python 3.7.0,多进程模块是 0.70.7 版;在 64 位 Anaconda 环境、Windows 10 上运行。

【问题讨论】:

  • 我不熟悉multiprocess,但听起来它没有正确序列化(或反序列化)print_time_and_value

标签: python multiprocessing global multiprocess


【解决方案1】:

我是multiprocess 作者。我看到你在 Windows 上......当你在 Windows 上运行时,我建议你使用freeze_support。我相信应该可以解决您所看到的NameError

import multiprocess as mp
import time

values = list(range(10))

def print_time_and_value(value):
    print(time.time(), value)


if __name__ == '__main__':

    mp.freeze_support()  # needed for Windows
    p = mp.Pool(4)
    p.map(print_time_and_value, values)

使用multiprocess,您的代码甚至可以在解释器中工作:

Python 3.7.3 (default, Mar 30 2019, 05:40:15) 
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import multiprocess as mp
>>> import time
>>> values = list(range(10))
>>> def print_time_and_value(value):
...     print(time.time(), value)
... 
>>> p = mp.Pool(4)
>>> _ = p.map(print_time_and_value, values)
1556681189.844021 0
1556681189.8443708 1
1556681189.8446798 2
1556681189.845576 4
1556681189.84569 5
1556681189.8458931 3
1556681189.846055 6
1556681189.846396 7
1556681189.846845 8
1556681189.847295 9
>>> 

请注意,我通常在函数中包含 import time,因为它使序列化更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    相关资源
    最近更新 更多