Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在一个单独的进程中运行。我可以统一包装器函数吗_Python_Multiprocessing_Wrapper - Fatal编程技术网

Python在一个单独的进程中运行。我可以统一包装器函数吗

Python在一个单独的进程中运行。我可以统一包装器函数吗,python,multiprocessing,wrapper,Python,Multiprocessing,Wrapper,我是Python新手,我想知道如何在语法上更有效地实现以下问题。 我有函数f1,f2。。。fN这些函数是产生新进程(目标为_f1,_f2,…_fN)的包装器, 将其参数(arg1,arg2,…)传递给子进程并接收返回值 对于这样的代码,我希望模块功能在不同的进程中执行,然后在调用者(模块的用户)进程中执行。 函数f1,f2。。。fN(分别为f1、f2、…)可能有不同的原型 in a module def _f1(arg1, arg2, ... argn, connection): .

我是Python新手,我想知道如何在语法上更有效地实现以下问题。 我有函数f1,f2。。。fN这些函数是产生新进程(目标为_f1,_f2,…_fN)的包装器, 将其参数(arg1,arg2,…)传递给子进程并接收返回值
对于这样的代码,我希望模块功能在不同的进程中执行,然后在调用者(模块的用户)进程中执行。
函数f1,f2。。。fN(分别为f1、f2、…)可能有不同的原型

in a module

def _f1(arg1, arg2, ... argn,  connection):
    ...
    connection.send(return_value)
    connection.close()
def f1(arg1, arg2, ... argn):
    parent_conn, child_conn = Pipe()
    p = Process(target=_f1, args=(arg1, arg2, ... argn, child_conn))
    p.start()
    p.join() 
    return parent_conn.recv()


def _f2(arg1, arg2, ... argm,  connection):
    ...
    connection.send(return_value)
    connection.close()    
def f2(arg1, arg2, ... argn):
    parent_conn, child_conn = Pipe()
    p = Process(target=_f2, args=(arg1, arg2, ... argm, child_conn))
    p.start()
    p.join() 
    return parent_conn.recv()

...

def _fn(arg1, arg2, ... argk,  connection):
    ...
    connection.send(return_value)
    connection.close()    
def fN(arg1, arg2, ... argn):
    parent_conn, child_conn = Pipe()
    p = Process(target=_fN, args=(arg1, arg2, ... argk, child_conn))
    p.start()
    p.join() 
    return parent_conn.recv()
很明显,包装函数f1、f2、fN大致相同。我是否可以将它们实现为单个包装器函数? 我希望执行过程不会受阻。例如,模块的用户应该能够同时执行f1和f2

我希望我已经设法解释了我的问题

下面是两个函数sum()和sin()的具体示例:

考虑到srj关于使用装饰的想法,我找到了下面发布的解决方案。 我试图进一步扩展它,以装饰connection.send(返回_值)和connection.close(),但它对我不起作用。下面是代码。用coments,我指定了哪些有效,哪些等价物(在我看来)无效。有什么帮助吗

from multiprocessing import Process, Pipe

def process_wrapper1(func):
    def wrapper(*args):
        parent_conn, child_conn = Pipe()
        f_args = args + (child_conn,)
        p = Process(target=func, args=f_args)
        p.start()
        p.join() 
        return parent_conn.recv()
    return wrapper

def process_wrapper2(func):
    def wrapper(*args):
        res=func(*args[0:len(args)-1])
        args[-1].send(res)
        args[-1].close()
    return wrapper



#def _sum(a, b,  connection):            #Working 
#   return_value=a+b
#   connection.send(return_value)
#   connection.close()
def __sum(a, b):                       #Doesn't work, see the error bellow
    return(a+b)    
_sum=process_wrapper2(__sum)

sum=process_wrapper1(_sum) 
Pyzo-ipython shell中的上述代码生成以下结果:

In [3]: import test1
In [4]: test1.sum(2,3)
---------------------------------------------------------------------------
PicklingError                             Traceback (most recent call last)
<ipython-input-4-8c542dc5e11a> in <module>()
----> 1 test1.sum(2,3)

C:\projects\PYnGUInLib\test1.py in wrapper(*args)
     11         f_args = (child_conn,) + args
     12         p = Process(target=func, args=f_args)
---> 13         p.start()
     14         p.join()
     15         return parent_conn.recv()

C:\pyzo2014a_64b\lib\multiprocessing\process.py in start(self)
    103                'daemonic processes are not allowed to have children'
    104         _cleanup()
--> 105         self._popen = self._Popen(self)
    106         self._sentinel = self._popen.sentinel
    107         _children.add(self)

C:\pyzo2014a_64b\lib\multiprocessing\context.py in _Popen(process_obj)
    210     @staticmethod
    211     def _Popen(process_obj):
--> 212         return _default_context.get_context().Process._Popen(process_obj)
    213 
    214 class DefaultContext(BaseContext):

C:\pyzo2014a_64b\lib\multiprocessing\context.py in _Popen(process_obj)
    311         def _Popen(process_obj):
    312             from .popen_spawn_win32 import Popen
--> 313             return Popen(process_obj)
    314 
    315     class SpawnContext(BaseContext):

C:\pyzo2014a_64b\lib\multiprocessing\popen_spawn_win32.py in __init__(self, process_obj)
     64             try:
     65                 reduction.dump(prep_data, to_child)
---> 66                 reduction.dump(process_obj, to_child)
     67             finally:
     68                 context.set_spawning_popen(None)

C:\pyzo2014a_64b\lib\multiprocessing\reduction.py in dump(obj, file, protocol)
     57 def dump(obj, file, protocol=None):
     58     '''Replacement for pickle.dump() using ForkingPickler.'''
---> 59     ForkingPickler(file, protocol).dump(obj)
     60 
     61 #

PicklingError: Can't pickle <function process_wrapper2.<locals>.wrapper at 0x0000000005541048>: attribute lookup wrapper on test1 failed
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)
EOFError: Ran out of input

In [5]: 
[3]中的
:导入test1
[4]中:test1.sum(2,3)
---------------------------------------------------------------------------
PicklingError回溯(最近一次调用上次)
在()
---->1测试1.总和(2,3)
包装中的C:\projects\pynguillib\test1.py(*args)
11 f_args=(子连接,)+args
12 p=进程(目标=函数,参数=f_参数)
--->13 p.开始
14 p.加入
15返回父节点连接记录()
C:\pyzo2014a\u 64b\lib\multiprocessing\process.py处于启动状态(self)
103“daemonic进程不允许有子进程”
104()
-->105 self.\u popen=self.\u popen(self)
106 self.\u sentinel=self.\u popen.sentinel
107_儿童。添加(自我)
C:\pyzo2014a\u 64b\lib\multiprocessing\context.py in\u Popen(process\u obj)
210@staticmethod
211 def_Popen(过程对象):
-->212返回_default_context.get_context().Process._Popen(Process_obj)
213
214类DefaultContext(BaseContext):
C:\pyzo2014a\u 64b\lib\multiprocessing\context.py in\u Popen(process\u obj)
311定义对象(过程对象):
312从.popen\u spawn\u win32导入popen
-->313返回Popen(过程对象)
314
315类生成上下文(BaseContext):
C:\pyzo2014a\u 64b\lib\multiprocessing\popen\u spawn\u win32.py in\uuuuu init\uuuj(self,process\u obj)
64尝试:
65减少。转储(准备数据,到子级)
--->66减少.转储(处理对象,到子对象)
67最后:
68上下文。设置\u生成\u popen(无)
转储中的C:\pyzo2014a\u 64b\lib\multiprocessing\reduce.py(obj、文件、协议)
57 def转储(obj,文件,协议=无):
58'''使用ForkingPickler替换pickle.dump()
--->59 ForkingPickler(文件、协议).dump(obj)
60
61 #
PicklingError:无法pickle:test1上的属性查找包装失败
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“C:\pyzo2014a\u 64b\lib\multiprocessing\spawn.py”,第106行,在spawn\u main中
出口代码=_主(fd)
文件“C:\pyzo2014a_64b\lib\multiprocessing\spawn.py”,第116行,在_main中
self=pickle.load(从父级)
EOFError:输入不足
在[5]中:
您可以使用创建流程并执行流程的样板文件来包装函数

def process_wrapper(func):
    def wrapper(*args):
        parent_conn, child_conn = Pipe()
        #attach the connection to the arguments
        f_args = args + (child_conn,)
        p = Process(target=func, args=f_args)
        p.start()
        p.join() 
        return parent_conn.recv()
    return wrapper
并将函数定义为

@process_wrapper
def _f2(arg1, arg2, ... argm,  connection):
    ...
    connection.send(return_value)
    connection.close()
解释:进程包装器函数采用一个具有N个位置参数的函数,最后一个位置参数始终是管道连接。它返回一个带有N-1个参数的函数,其中预先填充了连接

就你的具体职能而言

@process_wrapper
def sin(x,  connection):
   return_value=sin(x)
   connection.send(return_value)
   connection.close()  

@process_wrapper
def sum(a, b,  connection):
   return_value=a+b
   connection.send(return_value)
   connection.close()
您可以将函数调用为

sum(a,b)
更多关于python装饰器的参考 您应该使用。以下是一个例子:

def f1(*args):
    rv = do_calculations()
    return rv 

def f2(*args):
    ...

...
def fN(*args):
    ...

def worker(args):
    fn = args[0]
    return fn(*args[1:])

inputs = [
    [f1, f1_args],
    [f2, f2_args],
    ...
    [fN, fN_args]
]

pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
results = pool.map(worker, inputs)

嗨,srj,我想我了解了什么是装饰师,但我不明白在我的特殊情况下如何使用它们。在最初的问题中,我添加了一个具有两个函数的具体示例。你能用优化两个包装器sum()和sin()的decorators发布等价的代码吗?我已经对答案进行了编辑,如果这是你想要的,请看一下。嗨,srj,我在测试你的代码时出错了。无法pickle:它与test1.sum不是同一个对象。。。EOFError:输入用完了,我不确定问题出在哪里。我认为这是因为原来的功能是不可用的,在你的情况下,我们只有装饰版本。你还认为我想要的东西可以通过装饰来实现吗
def\u sum(a,b,connection):return\u value=a+b connection.send(return\u value)connection.close()
您可以执行sum=process\u wrapper(\u sum),而不是修饰函数。是的,这就是我尝试过的。请看我在原始问题末尾的代码。第一个装饰工作正常,但当我尝试使用另一个装饰时,它失败了,原因是
PicklingError:cannotpickle:attributelookup wrapper on test1失败了
。谢谢你,srj!嗨,乔尔,泳池似乎是个很好的工具,谢谢!实际上,我需要的是pool.apply\u async()。我无法在InteracticeShell中使用它,但这是我的项目的强烈要求。你认为这个问题可以解决吗?看看这个问题。它提供了在非交互式脚本中实现交互式解释器的工具。嗨,Joel,我想要的是能够使用ipython_QT控制台inte中的库
def f1(*args):
    rv = do_calculations()
    return rv 

def f2(*args):
    ...

...
def fN(*args):
    ...

def worker(args):
    fn = args[0]
    return fn(*args[1:])

inputs = [
    [f1, f1_args],
    [f2, f2_args],
    ...
    [fN, fN_args]
]

pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
results = pool.map(worker, inputs)