批量STEP 转 Stl

在C:\Program Files\FreeCAD 1.0\bin\freecad.exe下创建ptol.py

import sys
import os
import glob

# 确保不会被 freecadcmd 预解析
args = sys.argv

import FreeCAD
import Import
import Mesh

def convert_step_to_stl(step_file, stl_file):
    try:
        print(f"▶ 正在处理: {step_file}")
        doc = FreeCAD.newDocument()
        Import.open(step_file)
        FreeCAD.ActiveDocument.recompute()

        objects = FreeCAD.ActiveDocument.Objects
        if not objects:
            print(f"⚠️ 警告: 文件 {step_file} 没有几何体,跳过")
            FreeCAD.closeDocument(doc.Name)
            return False

        Mesh.export(objects, stl_file)
        FreeCAD.closeDocument(doc.Name)
        print(f"✅ 转换成功: {os.path.basename(step_file)} -> {os.path.basename(stl_file)}")
        return True
    except Exception as e:
        print(f"❌ 转换失败: {step_file},原因: {e}")
        return False

def batch_convert_step_to_stl(input_dir, output_dir):
    if not os.path.exists(input_dir):
        print(f"❌ 输入目录不存在: {input_dir}")
        return

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
        print(f"📂 创建输出目录: {output_dir}")

    # 找到所有 .step / .stp
    step_files = glob.glob(os.path.join(input_dir, "*.step")) + glob.glob(os.path.join(input_dir, "*.stp"))

    print(f"🔍 在 {input_dir} 中找到 {len(step_files)} 个STEP文件")
    if not step_files:
        print("⚠️ 没有找到STEP文件,请检查路径")
        return

    success, fail = 0, 0
    for step_file in step_files:
        file_name = os.path.splitext(os.path.basename(step_file))[0]
        stl_file = os.path.join(output_dir, file_name + ".stl")
        if convert_step_to_stl(step_file, stl_file):
            success += 1
        else:
            fail += 1

    print("\n========== 转换完成 ==========")
    print(f"✅ 成功: {success} 个")
    print(f"❌ 失败: {fail} 个")
    print(f"📂 输出目录: {output_dir}")

if __name__ == "__main__":
    if len(args) < 3:
        print("用法: python ptol.py <input_dir> <output_dir>")
        sys.exit(1)

    input_dir = os.path.abspath(args[1])
    output_dir = os.path.abspath(args[2])

    batch_convert_step_to_stl(input_dir, output_dir)

然后cmd

python.exe ptol.py D:\file\data2\steps D:\file\data2\stl_output

image

 

image

 

posted @ 2025-08-27 10:21  驼七  阅读(35)  评论(0)    收藏  举报