使用 mpi4py 在脚本中调用子进程

nil*_*que 5 python subprocess mpi4py

我在从 python 脚本调用外部程序时遇到问题,我想在其中使用 mpi4py 在不同处理器之间分配工作负载。

基本上,我想使用我的脚本,以便每个内核在不同的文件夹中准备一些用于计算的输入文件,然后在该文件夹中启动一个外部程序,等待输出,最后读取结果并收集它们。

但是,我根本无法使外部程序调用正常工作。在寻找这个问题的解决方案时,我发现我面临的问题似乎非常基本。下面的简单示例清楚地说明了这一点:

#!/usr/bin/env python
import subprocess

subprocess.call(“EXTERNAL_PROGRAM”, shell=True)
subprocess.call(“echo test”, shell=True)
Run Code Online (Sandbox Code Playgroud)

./script.py工作正常(两个调用都有效),而mpirun -np 1 ./script.py只输出test. 这种情况有什么解决方法吗?该程序肯定在我的 PATH 中,但如果我使用绝对路径进行调用,它也会失败。

这个问题似乎是相关的,遗憾的是没有答案......

编辑:

在我的问题的原始版本中,我没有包含任何使用 mpi4py 的代码,即使我在标题中提到了这个模块。所以这里是一个更详细的代码示例:

#!/usr/bin/env python

import os
import subprocess

from mpi4py import MPI


def worker(parameter=None):
    """Make new folder, cd into it, prepare the config files and execute the
    external program."""

    cwd = os.getcwd()
    dir = "_calculation_" + parameter
    dir = os.path.join(cwd, dir)
    os.makedirs(dir)
    os.chdir(dir)

    # Write input for simulation & execute
    subprocess.call("echo {} > input.cfg".format(parameter), shell=True)
    subprocess.call("EXTERNAL_PROGRAM", shell=True)

    # After the program is finished, do something here with the output files
    # and return the data. I'm using the input parameter as a dummy variable
    # for the processed output.
    data = parameter

    os.chdir(cwd)

    return data


def run_parallel():
    """Iterate over job_args in parallel."""

    comm = MPI.COMM_WORLD
    size = comm.Get_size()
    rank = comm.Get_rank()

    if rank == 0:
        # Here should normally be a list with many more entries, subdivided
        # among all the available cores. I'll keep it simple here, so one has
        # to run this script with mpirun -np 2 ./script.py
        job_args = ["a", "b"]
    else:
        job_args = None

    job_arg = comm.scatter(job_args, root=0)
    res = worker(parameter=job_arg)
    results = comm.gather(res, root=0)

    print res
    print results

if __name__ == '__main__':
    run_parallel()
Run Code Online (Sandbox Code Playgroud)

不幸的是,除了它是启用 MPI 的 C++ 应用程序之外,我无法提供外部可执行文件 EXTERNAL_PROGRAM 的更多详细信息。正如下面的评论部分所写,我怀疑这就是我的外部程序调用基本上被忽略的原因(或原因之一)。

请注意,我知道在这种情况下,没有人可以重现我的确切情况。尽管如此,我还是希望这里的某个人已经遇到了类似的问题并且能够提供帮助。

为完整起见,操作系统是 Ubuntu 14.04,我使用的是 OpenMPI 1.6.5。

Al *_*rad 1

在您的第一个示例中,您可能可以这样做:

\n\n
#!/usr/bin/env python\nimport subprocess\n\nsubprocess.call(\xe2\x80\x9cEXTERNAL_PROGRAM && echo test\xe2\x80\x9d, shell=True)\n
Run Code Online (Sandbox Code Playgroud)\n\n

python 脚本仅促进 MPI 调用。您也可以使用命令 \xe2\x80\x9cEXTERNAL_PROGRAM && echo test\xe2\x80\x9d 编写 bash 脚本,然后 mpirun bash 脚本;它相当于 mpi 运行 python 脚本。

\n\n

如果 EXTERNAL_PROGRAM 启用了 MPI,则第二个示例将不起作用。当使用 mpi4py 时,它将初始化 MPI。一旦以这种方式初始化 MPI 环境,就无法生成另一个 MPI 程序。您可以使用 MPI_Comm_spawn 或 MPI_Comm_spawn_multiple 和 mpirun 的 -up 选项生成。对于 mpi4py,请参阅计算 PI 示例生成示例(使用 MPI.COMM_SELF.Spawn)。

\n