ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

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

2019-09-29 02:55:46  阅读:289  来源: 互联网

标签:python ipython windows multiprocessing


我在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文件本身.

我的问题是:如果__name__ ==“__ main__”声明,如何在不将其置于此处的情况下运行多处理功能?

解决方法:

如果不运行if __name__ ==’__ main__’,多处理将无法工作.

但是,您可以使用多处理分支,它实质上利用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序列化程序增强的内置多处理程序,或者您可以使用Pool().apipe构建一个Queue,其中任何一个都更像您似乎对Queue感兴趣的内容.

获取悲情:https://github.com/uqfoundation

标签:python,ipython,windows,multiprocessing
来源: https://codeday.me/bug/20190929/1830169.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有