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

适用于主流操作系统的Shell脚本并行for循环实现方案

跨平台并行编译多个TeX文件的解决方案

方案一:Python脚本实现跨平台并行(推荐)

Python几乎在所有主流操作系统中都可直接使用,借助其multiprocessing模块能轻松实现并行编译,完全兼容Windows、macOS和Linux。

脚本示例

#!/usr/bin/env python3
import os
import subprocess
from multiprocessing import Pool

def compile_tex(file_path):
    # 定义编译流程,可按需添加bibtex、makeindex等步骤
    commands = [
        ["pdflatex", "-interaction=nonstopmode", file_path],
        ["pdflatex", "-interaction=nonstopmode", file_path]
        # 如需bibtex,取消下方注释:
        # ["bibtex", os.path.splitext(file_path)[0]]
    ]
    for cmd in commands:
        subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

if __name__ == "__main__":
    tex_files = [f for f in os.listdir(".") if f.endswith(".tex")]
    # 自动根据CPU核心数分配并行进程,也可手动指定,比如processes=4
    with Pool() as pool:
        pool.map(compile_tex, tex_files)

使用说明

  1. 将代码保存为parallel_tex_compile.py
  2. 在终端执行:python3 parallel_tex_compile.py(Windows可在命令提示符/PowerShell中运行)
  3. 可根据实际编译需求修改commands列表,调整编译步骤和参数。

方案二:跨平台Shell兼容方案

如果偏好Shell脚本,可采用后台进程+等待机制,需注意不同系统的终端环境:

  • Linux/macOS直接用Bash;Windows需通过Git Bash、WSL或PowerShell执行Bash脚本

脚本示例

#!/bin/bash
TEX_FILES=(*.tex)

compile_tex() {
    local file="$1"
    # 多次编译流程,按需调整
    pdflatex -interaction=nonstopmode "$file"
    pdflatex -interaction=nonstopmode "$file"
    # 如需bibtex,取消下方注释:
    # bibtex "${file%.tex}"
}

# 启动所有编译任务到后台
for file in "${TEX_FILES[@]}"; do
    compile_tex "$file" &
done
# 等待所有后台任务完成
wait

使用说明

  • Windows环境需确保TeX发行版(如TeX Live、MikTeX)已配置环境变量,且终端支持Bash语法。
  • macOS/Linux直接在终端执行bash script.sh即可。

关键注意事项

  • 所有平台需确保pdflatex、bibtex等工具在系统PATH中,否则编译会失败。
  • 若多个TeX文件依赖相同的辅助文件(如共享.bib),需避免并行冲突,可减少并行进程数或单独处理这类文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:52:15