我无法从我的 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 中,但如果我使用绝对路径进行调用,它也会失败。
编辑:
在我的问题的原始版本中,我没有包含任何使用 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。