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

如何用Python循环生成带不同参数的SLURM批量作业脚本

批量生成SLURM作业脚本并提交(按年份拆分)

针对你需要按年份拆分生成独立SLURM作业脚本并提交的需求,以下提供两种简单可行的实现方式:

一、Python脚本实现

这个脚本会遍历指定年份范围,自动生成对应年份的.sl作业文件,并且生成后直接提交作业:

import subprocess

# 设置年份范围,替换成你需要的42年区间
start_year = 1982
end_year = 2023

# SLURM作业模板,注意替换其中的MYFOLDER、pythonfilename.py等为你的实际内容
slurm_template = """#!/bin/bash -l
# The -l above is required to get the full environment with modules
# Set the allocation to be charged for this job
# not required if you have set a default allocation
#SBATCH -A MYFOLDER
# The name of the job
#SBATCH -J jobName{year}
# 24 hour wall-clock time will be given to this job
#SBATCH -t 3:00:00
# Job partition
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=6
#SBATCH --mem=30GB
#SBATCH -p main
# load the anaconda module
ml PDC/21.11
ml Anaconda3/2021.05
conda activate myEnv
python pythonfilename.py {year}
"""

for year in range(start_year, end_year + 1):
    # 生成作业文件名
    job_filename = f"jobName{year}.sl"
    # 填充模板内容
    with open(job_filename, "w") as f:
        f.write(slurm_template.format(year=year))
    # 赋予脚本执行权限
    subprocess.run(["chmod", "+x", job_filename])
    # 提交作业
    subprocess.run(["sbatch", job_filename])
    print(f"已生成并提交作业:{job_filename}")

二、Bash脚本实现

如果你更习惯用Bash,这个脚本同样可以完成生成+提交的操作:

#!/bin/bash

# 设置年份范围,替换成你的实际区间
start_year=1982
end_year=2023

# 遍历年份
for year in $(seq $start_year $end_year); do
    job_file="jobName${year}.sl"
    # 写入SLURM作业内容,替换占位符
    cat > $job_file << EOF
#!/bin/bash -l
# The -l above is required to get the full environment with modules
# Set the allocation to be charged for this job
# not required if you have set a default allocation
#SBATCH -A MYFOLDER
# The name of the job
#SBATCH -J jobName${year}
# 24 hour wall-clock time will be given to this job
#SBATCH -t 3:00:00
# Job partition
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=6
#SBATCH --mem=30GB
#SBATCH -p main
# load the anaconda module
ml PDC/21.11
ml Anaconda3/2021.05
conda activate myEnv
python pythonfilename.py ${year}
EOF
    # 添加执行权限
    chmod +x $job_file
    # 提交作业
    sbatch $job_file
    echo "已生成并提交作业:$job_file"
done

三、单独批量提交已生成的作业脚本

如果你已经提前生成了所有.sl文件,只需执行以下Bash命令即可批量提交:

# 方式1:按年份遍历提交
for year in $(seq 1982 2023); do
    sbatch jobName${year}.sl
done

# 方式2:直接匹配所有jobName开头的.sl文件提交
for job_file in jobName*.sl; do
    sbatch $job_file
done

注意:所有脚本中的MYFOLDER、pythonfilename.py、年份区间等内容,请替换为你的实际信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:01:42