使用mpi4py在脚本中调用子进程
我无法从我的
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只输出测试.这种情况有没有解决方法?该程序肯定在我的PATH中,但如果我使用该通话的绝对路径,它也会失败. This SO question seems to be related,sadly there are no answers… 编辑: 在我的问题的原始版本中,我没有包含使用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. 解决方法
在您的第一个示例中,您可以执行此操作:
#!/usr/bin/env python import subprocess subprocess.call(“EXTERNAL_PROGRAM && echo test”,shell=True) python脚本只是为了方便MPI调用.您也可以使用命令“EXTERNAL_PROGRAM&& amp; echo test“和mpirun bash脚本;它等同于mpirunning python脚本. 如果EXTERNAL_PROGRAM启用了MPI,则第二个示例将不起作用.使用mpi4py时,它将初始化MPI.一旦以这种方式初始化MPI环境,就无法生成另一个MPI程序.您可以使用MPI_Comm_spawn或MPI_Comm_spawn_multiple和-up选项生成mpirun.对于mpi4py,请参阅Compute PI example进行产卵(使用MPI.COMM_SELF.Spawn). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |