如何让函数在 Python 中作为子进程运行? [英] How do I make functions run as subprocesses in Python?

查看:57
本文介绍了如何让函数在 Python 中作为子进程运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 Python 脚本能够将其功能之一作为子进程运行.我该怎么做?

I want my Python script to be able to run one of its functions as subprocesses. How should I do that?

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

Here is a mock-up script of my intention:

#!/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))

感谢您的建议.对我来说,正确地提出问题,从而进行适当的网络搜索,对我来说有点困难.

Thank you for your suggestions. It is a little hard for me to formulate the problem correctly, and thus to make the appropriate web search.

推荐答案

使用多处理模块:>

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 迭代的列表很长时.在这种情况下,更好的方法是使用多处理池:


You might not want to be creating one process for each call to print_mynumber, especially if the list foo iterates over is long. A better way in that case would be to use a multiprocessing pool:

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 命令非常相似,不同之处在于它将任务分给工作池.

The pool, be default, will create N worker processes, where N is the number of cpus (or cores) the machine possesses. pool.map behaves much like the Python builtin map command, except that it farms out tasks to the pool of workers.

这篇关于如何让函数在 Python 中作为子进程运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆