如何使运行在Python的子进程的功能呢?(How do I make functions run

2019-08-01 07:18发布

我希望我的Python脚本能够运行其功能之一作为子。 我应该怎么办呢?

这里是我的意图的模拟脚本:

#!/urs/bin/env python

def print_mynumber(foo):
    """This function is obviously more complicated in my script.
    It should be run as a subprocess."""
    print(foo)

for foo in [1,2,3]:
    print_mynumber(foo) # Each call of this function should span a new process.
    # subprocess(print_mynumber(foo))

谢谢你的建议。 这是一个有点难受,正确制定问题,从而做出相应的Web搜索。

Answer 1:

使用多模块 :

import multiprocessing as mp

def print_mynumber(foo):
    """This function is obviously more complicated in my script.
    It should be run as a subprocess."""
    print(foo)

if __name__ == '__main__':
    for foo in [1,2,3]:
        proc = mp.Process(target = print_mynumber, args = (foo, ))
        proc.start()

你可能不希望创建每次调用一个过程print_mynumber ,特别是如果该列表foo遍历长。 在这种情况下,更好的办法是使用一个多池:

import multiprocessing as mp

def print_mynumber(foo):
    """This function is obviously more complicated in my script.
    It should be run as a subprocess."""
    print(foo)

if __name__ == '__main__':
    pool = mp.Pool()
    pool.map(print_mynumber, [1,2,3])

池,是默认值,将创建n个工作进程,其中N是的CPU(或核心)的数量的机器具备。 pool.map行为很像Python的内置map命令,除了它农场出来的任务工人的游泳池。



文章来源: How do I make functions run as subprocesses in Python?