5

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

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

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

#!/usr/bin/env python
import subprocess

subprocess.call(“EXTERNAL_PROGRAM”, shell=True)
subprocess.call(“echo test”, shell=True)

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

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

编辑:

在我的问题的原始版本中,我没有包含任何使用 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()

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

请注意,我知道在这种情况下,没有人可以重现我的确切情况。但是,我仍然希望这里有人已经遇到过类似的问题并且可能能够提供帮助。

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

4

1 回答 1

1

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

#!/usr/bin/env python
import subprocess

subprocess.call(“EXTERNAL_PROGRAM && echo test”, shell=True)

python 脚本只是促进 MPI 调用。您也可以使用命令“EXTERNAL_PROGRAM && echo test”编写一个 bash 脚本,然后运行 ​​bash 脚本;它相当于 mpirunning python 脚本。

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

于 2015-12-04T21:45:16.670 回答