我需要一些控制子流程的帮助.

目前,我正在使用python控制软件的运行,如下面的代码所示.

import subprocess

# Declaring some input and output names for the third-party program
label = ['fname1', 'fname2', 'fname3', 'fname4']
input_list = [ 'inp.'+ l for l in label ]
output_list = [ 'out.'+ l for l in label ]

# Run all sets of input and output using the third-party software
for in, out in zip(input_list, output_list):
    #The bash command to run the executable
    command = f"mpirun pw.x < {in} > {out}" 
    subprocess.run(command, shell=True)

我的计算机有64个逻辑核,正如我用软件测试的那样,使用32和64不会改变计算速度,因此,我想编辑代码以适应两个并发子进程.跑mpirun -n 32 ...码.

我不知道如何进行并发操作,比如排队和控制在给定时间允许运行多少子流程实例.

请问哪个模块/库可以帮助我完成这项工作?当然,非常感谢您提供一个代码示例.

另外,PBS/SLURM系统不是一个选项,因为我还在python脚本中做一些处理工作.

谢谢

推荐答案

如果要并行运行mpirun -n 32次,请try 以下方法:

import concurrent.futures

labels = ['fname1', 'fname2']
with concurrent.futures.ProcessPoolExecutor(max_workers=len(labels)) as pool:
    for label in labels:
        command = f"mpirun -n 32 pw.x < inp.{label} > out.{label}"
        pool.submit(subprocess.run, command, shell=True)

with语句将在最后关闭池,这使它等待所有作业(job)完成.

Python-3.x相关问答推荐

DuckDB:带有嵌套对象的星形表达式

Python根据阈值对数字进行分组

Python将类实例变量转换为嵌套 struct

Python VS Code 自动导入路径包含 src

在特定条件下从 DataFrame 中提取特定组

切片的Python复杂性与元组的星号相结合

Pandas:从 Pandas 数据框中的 1 和 0 模式中获取值和 ID 的计数

使用 selenium 加速网页抓取

为什么最简单的流光示例会出错?

Semaphore信号量 Python 的工作原理

是否将dict转换为一个数据帧,每个值都有重复的键?

Pytorch:图像标签

内部如何使用 Python 语法?

预分配一个无列表

迭代器也是可迭代的吗?

判断 dict.items() 中的成员资格的时间复杂度是多少?

混合全局/参数和名为top的函数的奇怪python行为

向 Python 函数添加属性的最佳方法

当默认 pip 为 pip2 时,升级 pip3 的正确格式是什么?

python - Pandas - Dataframe.set_index - 如何保留旧的索引列