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

如何修改Python代码,实现作业执行后复制输出文件到下一个目录并循环执行?

修改Python脚本实现作业目录间的restart.dat传递执行

你的需求是按顺序执行每个目录的CFD作业,每完成一个目录的任务后,将生成的restart.dat复制到下一个目录作为输入,循环完成所有目录的作业。以下是修改后的代码及关键说明:

修改后的完整代码

import os
import shutil
import subprocess

basedir = os.path.join('/scratch', 'run')
# 作业目录列表
aoa = ['08deg', '09deg', '10deg']

for idx, dir_name in enumerate(aoa):
    current_path = os.path.join(basedir, dir_name)
    print(f"Current working directory: {current_path}")
    
    # 构建作业命令,在指定目录执行
    cmd = ["time", "mpirun", "-np", "1008", "SU2_CFD", "turb_low_cfl.cfg"]
    # 执行作业并将输出写入restart.dat
    with open(os.path.join(current_path, "restart.dat"), "w") as out_file:
        result = subprocess.run(cmd, cwd=current_path, stdout=out_file, stderr=subprocess.STDOUT)
        # 检查作业是否执行成功
        if result.returncode != 0:
            print(f"Error: Job in {current_path} failed with return code {result.returncode}")
            break  # 作业失败时终止循环,可根据需求调整
    
    # 如果不是最后一个目录,复制restart.dat到下一个目录
    if idx < len(aoa) - 1:
        next_dir = os.path.join(basedir, aoa[idx+1])
        source_file = os.path.join(current_path, "restart.dat")
        dest_file = os.path.join(next_dir, "restart.dat")
        
        # 检查源文件是否存在
        if os.path.exists(source_file):
            shutil.copy2(source_file, dest_file)
            print(f"Copied restart.dat from {current_path} to {next_dir}")
        else:
            print(f"Warning: restart.dat not found in {current_path}, skip copying")
            break  # 文件不存在时终止循环,可根据需求调整

关键修改点说明

  • 替换os.system为subprocess.run:更安全可控,能指定作业执行的工作目录(cwd参数),无需切换全局工作目录,同时可以捕获进程返回值检查作业是否成功。
  • 文件复制逻辑:在每个作业执行完成后,判断当前是否为最后一个目录,若不是则用shutil.copy2将restart.dat复制到下一个目录(copy2会保留文件的元数据,比shutil.copy更适合这类场景)。
  • 错误检查:增加了作业执行返回值检查和源文件存在性检查,避免后续步骤因为前置失败而无效执行。
  • 路径处理:全程使用绝对路径操作,避免因工作目录切换导致的路径错误。

内容的提问来源于stack exchange,提问作者kaush

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:27:02