【问题标题】:multiprocessing package in interactive Python交互式 Python 中的多处理包
【发布时间】:2015-03-12 01:10:42
【问题描述】:

我有以下代码test.py:

#multiprocessing in the interactive Python 

import time
from multiprocessing import Process, Pipe

def MyProcess(a):

    while(1):
       time.sleep(1)
       a.send("tic")    

if __name__ == "__main__":

    a, b = Pipe() 

    p = Process(target=MyProcess, args=(a,))
    p.start()

    while(1):
       msg=b.recv()
       print(msg)

如果我在 DOS shell "python test.py" 中执行它就可以正常工作 但如果我使用 IEP (Pyzo) 中的“执行文件”,它就不起作用。

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\pyzo2014a_64b\lib\multiprocessing\spawn.py", line 106, in spawn_main
    exitcode = _main(fd)
  File "C:\pyzo2014a_64b\lib\multiprocessing\spawn.py", line 116, in _main
    self = pickle.load(from_parent)
AttributeError: Can't get attribute 'MyProcess' on <module '__main__' (built-in)>

我发现这是一个记录在案的“问题”。请检查以下链接的答案。

multiprocessing breaks in interactive mode

这是否意味着我不应该使用交互式 Python 中的多处理包?这是否意味着我无法从 IPython 控制台创建进程? 对此的任何澄清将不胜感激

【问题讨论】:

    标签: python multiprocessing interactive


    【解决方案1】:

    正确,您不能在解释器中使用multiprocessing……主要是因为pickle 不知道如何序列化交互函数。但是,如果您使用称为pathos.multiprocessingmultiprocessing fork,您可以从解释器中执行您想要的操作。这是因为pathos.multiprocessing 使用dill,而dill 知道如何序列化解释器中定义的函数(和其他对象)。

    >>> from pathos.multiprocessing import ProcessingPool as Pool
    >>> 
    >>> p = Pool(4)
    >>> def squared(x):
    ...   return x**2
    ... 
    >>> def pow(x,y):
    ...   return x**y
    ... 
    >>> a = range(10)
    >>> b = range(10,0,-1)
    >>> 
    >>> p.map(squared, a)
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    >>> res = p.amap(pow, a, b)
    >>> print "asynchronous, and with multiple inputs!"
    asynchronous, and with multiple inputs!
    >>> res.get()
    [0, 1, 256, 2187, 4096, 3125, 1296, 343, 64, 9]
    

    在此处获取pathoshttps://github.com/uqfoundation

    【讨论】:

    • 一个新的pathos 版本即将发布。现有的稳定版本已经很老了,早于pip,但是使用setuptools 可以轻松安装。
    • 谢谢你,Mike,我会伤心地看看并报告。
    猜你喜欢
    • 2014-08-19
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多