Windows 机器上的 IPython 控制台中的多处理 - 如果 __name_ 要求

multiprocessing in IPython console on Windows machine - if __name_ requirement

我在 Windows 机器上使用 IPython 和 Spyder IDE。 IDE 启动时,会加载一组 py 文件来定义一些函数,使我的工作更轻松一些。一切都按预期工作。

现在我想升级其中一个函数以使用多处理,但是在 Windows 上这需要 if __name__ == "__main__": 语句。所以似乎我不能直接调用函数并从 IPython 控制台传递参数。

例如,其中一个 py 文件(我们称之为 test.py)可能类似于以下代码。

import multiprocessing as mp
import random
import string

# define a example function
def rand_string(length, output):
    """ Generates a random string of numbers, lower- and uppercase chars. """
    rand_str = ''.join(random.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
                + string.digits)
           for i in range(length))
    output.put(rand_str)


def myFunction():
    # Define an output queue
    output = mp.Queue()        

    # Setup a list of processes that we want to run
    processes = [mp.Process(target=rand_string, args=(5, output)) for x in range(4)]

    # Run processes
    for p in processes:
        p.start()

    # Exit the completed processes
    for p in processes:
        p.join()

    # Get process results from the output queue
    results = [output.get() for p in processes]

    print(results)

在我的 IPython 控制台中,我想使用行

myFunction()

触发所有计算。但是在 Windows 上,最终出现了 BrokenPipe 错误。

当我把

if __name__ == "__main__":
     myFunction()

在 py 文件的末尾和 运行 完整的文件

runfile(test.py)

有效。当然。但这使得向函数传递参数变得非常困难,因为我总是必须编辑 test.py-文件本身。

我的问题是:如何在不将其放入此 if __name__ == "__main__": 语句中的情况下获取多处理函数 运行ning??

如果没有 运行 if __name__ == '__main__'.

multiprocessing 将不起作用

但是,您可以使用 multiprocessing 的一个分支,它本质上利用 dill 将解释器会话视为一个文件……(简而言之,它有效)。

Python 2.7.9 (default, Dec 11 2014, 01:21:43) 
Type "copyright", "credits" or "license" for more information.

IPython 3.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from pathos.multiprocessing import ProcessingPool as Pool

In [2]: def squared(x):
   ...:     return x**2
   ...: 

In [3]: x = range(10)

In [4]: p = Pool()

In [5]: p.map(squared, x)
Out[5]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [6]: res = p.imap(squared, x)

In [7]: list(res)
Out[7]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [8]: 

您也可以使用由 dill 序列化程序增强的内置 multiprocessing,或者您可以使用 Pool().apipe 构建 Queue,其中任何一个更像是您似乎对 Queue.

感兴趣的事情

在此处获取悲情:https://github.com/uqfoundation

所以,我解决了那个具体问题。

  1. rand_string的定义放在一个单独的文件里,叫做 test2.

  2. test2 作为模块导入到我的 test.py 脚本中

    import test2 as test2

  3. 修改以下行以访问test2模块

    processes = [mp.Process(target=test2.rand_string, args=(5, output)) for x in range(4)]
    
  4. 运行 test.py

  5. 致电myFunction()

  6. 开心:)

解决方案基于这个multiprocessing tutorial,建议从另一个脚本导入目标函数。此解决方案绕过 if __name__ -wrapper 的安全自导入以访问目标函数。