You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python循环实现rung09计算任务逐个自动化执行

逐个执行rung09计算任务的Python实现

背景

我在共享Unix机器上执行计算任务,使用机器配置的rung09命令启动计算,命令格式如下:

rung09 <无扩展名的文件名>

执行该命令后,会在当前目录生成与目标文件同名的.log文件,用于存储计算数据。由于有超过1000个计算文件,为避免机器过载,需要实现逐个串行执行这些任务。

最初的实现思路:

  • 进入目标计算目录
  • 遍历目录中的文件,提取无扩展名的文件名存入列表
  • 循环遍历列表,依次执行rung09命令

最终实现脚本

问题已解决,以下是可直接使用的Python脚本:

import os
import subprocess
import time

# 目标计算目录
diretorio = "/usr/home/joao_pedro/input/calculos/"

os.chdir(diretorio)

def check_termination(file_path):
    """检查计算任务是否已终止(正常完成或报错终止)"""
    with open(file_path, 'r') as log_file:
        content = log_file.read()
        normal_termination_count = content.count("Normal termination")
        error_termination_count = content.count("Error termination")
        
        # 依据Gaussian日志特征判断任务状态
        if normal_termination_count >= 2 or error_termination_count >= 1:
            return True
        return False

# 列出目录下所有条目
nomes_arquivos = os.listdir()

# 筛选文件(排除目录)并提取无扩展名的文件名
arquivos = [nome.split('.')[0] for nome in nomes_arquivos if os.path.isfile(os.path.join(diretorio, nome))]

# 排序文件名,保证执行顺序稳定
files = sorted(arquivos)

for file in files:
    # 启动计算任务
    subprocess.run(["rung09", file])
    log_file_path = os.path.join(diretorio, f"{file}.log")
    
    # 等待日志文件生成
    time.sleep(5)

    # 轮询检查任务是否终止,未完成则每隔5秒重试
    while not check_termination(log_file_path):
        time.sleep(5)

脚本说明

  • 终止检查逻辑:通过读取计算日志中的特征标记,精准判断任务是正常完成还是报错终止,确保前一个任务彻底结束后再启动下一个。
  • 串行执行机制:完全避免多任务并行导致的机器过载问题,适合大规模计算文件的分批处理。
  • 稳定排序:对文件名排序后执行,避免每次运行的任务顺序随机。

内容的提问来源于stack exchange,提问作者feyn.py

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 04:56:28