📖 概述
AnyCAD NEXT 提供了两种强大的自动化建模方式:PyScript 脚本建模和 CLI 命令行建模。这两种方式各有优势,可以满足不同场景下的 CAD 自动化需求。本文将深入介绍这两种建模方式的特点、使用方法和最佳实践。
🎯 为什么需要自动化建模?
在传统 CAD 工作中,设计师需要通过图形界面手动操作来完成建模任务。这种方式存在以下问题:
• ❌ 重复性工作多:相似零件需要反复操作 • ❌ 容易出错:人工操作可能出现尺寸错误 • ❌ 难以批量处理:无法快速生成多个变体 • ❌ 知识难以传承:设计经验难以固化
自动化建模通过代码或命令来驱动 CAD 系统,可以:
• ✅ 提高效率:秒级完成复杂建模 • ✅ 保证质量:代码执行无误差 • ✅ 批量处理:一次生成数百个变体 • ✅ 知识沉淀:建模逻辑可版本管理
💻 PyScript 脚本建模
什么是 PyScript?
PyScript 是基于 Python 的脚本建模方式,通过 anycad_next SDK 直接调用 AnyCAD NEXT 的 API。它提供了完整的编程能力,适合复杂的建模逻辑。
核心特性
1. 完整的 Python 生态
import mathimport anycad_next as ac# 可以使用所有 Python 库import numpy as npfrom typing importList,Optional2. 面向对象的设计
with ac.Application.launch()as app:# 文档管理 doc = app.documents.create("MyDesign")# 零件管理 part = doc.parts.create("Base")# 草图创建 sketch = part.sketches2d.create("Profile", plane="XY")# 特征建模 extrude = part.features.extrude(sketch).with_height(20).build("BaseExtrude")3. 异步任务处理
# SDK 自动处理异步任务sketch = part.sketches2d.create("Sketch1", plane="XY")extrude = part.features.extrude(sketch).with_height(20).build("Extrude1")# 同样自动处理异步流程完整示例:创建带孔的法兰盘
"""创建带螺栓孔的法兰盘"""import anycad_next as acimport mathdefcreate_flange():with ac.Application.launch()as app:# 1. 创建文档和零件 doc = app.documents.create("FlangeDesign") part = doc.parts.create("Flange")# 2. 创建主轮廓草图(圆形) main_sketch = part.sketches2d.create("MainProfile", plane="XY") main_sketch.geometry.create_circle("OuterCircle",(0,0),50) main_sketch.geometry.create_circle("InnerCircle",(0,0),20) main_sketch.close()# 3. 拉伸主体 base_extrude = part.features.extrude(main_sketch).with_height(10).build("BaseBody")# 4. 创建螺栓孔草图 hole_sketch = part.sketches2d.create("HolePattern", plane="XY")# 在圆周上均匀分布 6 个孔 num_holes =6 radius =35for i inrange(num_holes): angle =2* math.pi * i / num_holes x = radius * math.cos(angle) y = radius * math.sin(angle) hole_sketch.geometry.create_circle(f"Hole{i+1}",(x, y),5) hole_sketch.close()# 5. 拉伸切除(创建通孔) hole_cut = part.features.extrude(hole_sketch).with_height(10).with_direction_type(1).build("HoleCut")# 6. 添加倒角 fillet = part.features.fillet().with_base(base_extrude.id).with_radius(2).build("EdgeFillet")print(f"✅ 法兰盘创建完成!")print(f" - 主体 ID: {base_extrude.id}")print(f" - 螺栓孔数量: {num_holes}")print(f" - 倒角 ID: {fillet.id}")if __name__ =="__main__": create_flange()PyScript 的优势
适用场景
• ✅ 参数化设计系统 • ✅ 复杂几何算法 • ✅ 批量生成变体 • ✅ 与外部系统集成 • ✅ 需要数据处理的场景
⚡ CLI 命令行建模
什么是 CLI?
CLI(Command-Line Interface)是通过命令行工具 acad-cli 来执行建模操作。它将常用的建模功能封装为简洁的命令,适合快速操作和批处理。
核心特性
1. 简洁的命令语法
# 创建文档acad-cli document create --name "MyDesign"# 创建零件acad-cli part create --name "Base"# 创建草图acad-cli sketch create --name "Profile"--plane XY# 创建几何对象acad-cli sketch geometry line --sketch-name "Profile" \--name "Line1"--start "0,0"--end "100,0"# 创建特征acad-cli feature extrude --sketch-name "Profile" \--height 20--name "BaseExtrude"2. 批处理支持
创建批处理脚本 flange.txt:
# 创建法兰盘的批处理脚本# 1. 创建文档和零件document create --name "FlangeDesign"part create --name "Flange"# 2. 创建主轮廓sketch create --name "MainProfile"--plane XYsketch geometry circle --sketch-name "MainProfile"--name "OuterCircle"--center "0,0"--radius 50sketch geometry circle --sketch-name "MainProfile"--name "InnerCircle"--center "0,0"--radius 20sketch close --name "MainProfile"# 3. 拉伸主体feature extrude --sketch-name "MainProfile"--height 10--name "BaseBody"# 4. 创建螺栓孔模式sketch create --name "HolePattern"--plane XYsketch geometry circle --sketch-name "HolePattern"--name "Hole1"--center "35,0"--radius 5sketch geometry circle --sketch-name "HolePattern"--name "Hole2"--center "17.5,30.31"--radius 5sketch geometry circle --sketch-name "HolePattern"--name "Hole3"--center "-17.5,30.31"--radius 5sketch geometry circle --sketch-name "HolePattern"--name "Hole4"--center "-35,0"--radius 5sketch geometry circle --sketch-name "HolePattern"--name "Hole5"--center "-17.5,-30.31"--radius 5sketch geometry circle --sketch-name "HolePattern"--name "Hole6"--center "17.5,-30.31"--radius 5sketch close --name "HolePattern"# 5. 拉伸切除feature extrude --sketch-name "HolePattern"--height 10--name "HoleCut"# 6. 添加倒角feature fillet --base-name "BaseBody"--radius 2--name "EdgeFillet"执行批处理:
acad-cli batch run --file flange.txt输出:
Found18 command(s)in script[1/18]Line4Command: document create --name "FlangeDesign"Status:[OK] SUCCESS[2/18]Line5Command: part create --name "Flange"Status:[OK] SUCCESS...[18/18]Line30Command: feature fillet --base-name "BaseBody"--radius 2--name "EdgeFillet"Status:[OK] SUCCESS============================================================BATCH EXECUTION SUMMARY============================================================Total commands:18[OK]Success:18[FAIL]Failed:0============================================================3. JSON 输出格式(适合 AI Agent)
acad-cli document create --name "Test"--json-output输出:
{"id":"59770761287700480","name":"Test","status":"created"}4. 跨平台支持
# Windows.\acad-cli.exe document create --name "Test"# Linux/Mac./acad-cli document create --name "Test"# Dockerdocker run anycad-cli document create --name "Test"CLI 的优势
适用场景
• ✅ 快速原型设计 • ✅ 标准化建模流程 • ✅ CI/CD 集成 • ✅ AI Agent 调用 • ✅ 非程序员使用
🔄 两种方式对比
| 学习曲线 | ||
| 灵活性 | ||
| 复杂度支持 | ||
| 执行速度 | ||
| 调试难度 | ||
| 批处理能力 | ||
| 集成难度 | ||
| AI 集成 | ||
| 适用人群 |
🎯 最佳实践
1. 选择合适的建模方式
选择 PyScript,如果:
• 需要复杂的几何算法 • 需要与外部系统交互 • 需要参数化设计框架 • 团队成员有 Python 基础
选择 CLI,如果:
• 快速验证想法 • 标准化操作流程 • 与非技术人员协作 • 集成到 CI/CD 流程
2. 混合使用策略
# PyScript 中调用 CLIimport subprocessdefbatch_process():"""批量处理多个零件""" designs =["Part_A","Part_B","Part_C"]for design in designs:# 使用 CLI 执行标准流程 result = subprocess.run(["acad-cli","batch","run","--file",f"templates/{design}.txt"], capture_output=True, text=True)if result.returncode ==0:print(f"✅ {design} 创建成功")else:print(f"❌ {design} 创建失败: {result.stderr}")3. 版本控制
# 将建模脚本纳入 Git 管理git add scripts/create_flange.pygit add templates/flange.txtgit commit -m "Add flange design template"4. 模板化设计
# PyScript 模板classParametricPart:def__init__(self, length=100, width=50, height=20): self.length = length self.width = width self.height = heightdefbuild(self):with ac.Application.launch()as app: doc = app.documents.create(f"Part_{self.length}x{self.width}") part = doc.parts.create("Base")# ... 使用参数建模 ...# CLI 模板(使用占位符)document create --name "{{NAME}}"part create --name "Base"sketch create --name "Profile"--plane XYsketch geometry rectangle --sketch-name "Profile" \--width {{WIDTH}}--height {{HEIGHT}}feature extrude --sketch-name "Profile"--height {{DEPTH}}5. 性能优化
# PyScript:设置请求间隔with ac.Application.launch(request_interval=0.3)as app:# 批量创建时避免频繁请求for i inrange(100): doc = app.documents.create(f"Doc_{i}")# CLI:设置全局间隔acad-cli --request-interval 0.3 batch run --file large_script.txt🚀 实际案例
案例 1:齿轮参数化设计(PyScript)
"""参数化齿轮生成器"""import anycad_next as acimport mathdefcreate_gear(module=2, teeth=20, width=10):""" 创建渐开线齿轮 Args: module: 模数 teeth: 齿数 width: 齿宽 """with ac.Application.launch()as app: doc = app.documents.create(f"Gear_m{module}_z{teeth}") part = doc.parts.create("Gear")# 计算齿轮参数 pitch_diameter = module * teeth addendum = module dedendum =1.25* module# 创建齿廓草图 sketch = part.sketches2d.create("ToothProfile", plane="XY")# 绘制单个齿的渐开线轮廓# ... 复杂的几何计算 ... sketch.close()# 旋转生成齿轮 gear_body = part.features.revolve(sketch).with_angle(360).build("GearBody")print(f"✅ 齿轮创建完成:模数={module}, 齿数={teeth}")return gear_body# 生成一系列齿轮for teeth in[15,20,25,30]: create_gear(module=2, teeth=teeth, width=10)案例 2:标准件库批量生成(CLI)
创建 generate_std_parts.sh:
#!/bin/bash# 批量生成标准件# 生成 M6 螺栓acad-cli batch run --file templates/bolt_M6.txt# 生成 M8 螺栓acad-cli batch run --file templates/bolt_M8.txt# 生成 M10 螺栓acad-cli batch run --file templates/bolt_M10.txt# 生成螺母for size in M6 M8 M10;do acad-cli batch run --file templates/nut_${size}.txtdoneecho"✅ 所有标准件生成完成!"案例 3:AI Agent 集成(CLI + JSON)
# AI Agent 调用 CLIimport subprocessimport jsondefai_create_part(specification:dict):""" AI 根据自然语言描述创建零件 Args: specification: { "type": "box", "dimensions": {"length": 100, "width": 50, "height": 20}, "features": ["fillet", "hole"] } """# 1. AI 解析需求,生成 CLI 命令 commands = generate_cli_commands(specification)# 2. 执行命令for cmd in commands: result = subprocess.run( cmd.split(), capture_output=True, text=True)# 3. 解析 JSON 输出if result.returncode ==0: output = json.loads(result.stdout)print(f"Created: {output['name']} (ID: {output['id']})")else:raiseException(f"Failed: {result.stderr}")# 使用示例ai_create_part({"type":"box","dimensions":{"length":100,"width":50,"height":20},"features":[{"type":"fillet","radius":2},{"type":"hole","diameter":10,"position":[50,25]}]})🔮 未来展望
1. WebAssembly 支持
未来可能支持在浏览器中运行 PyScript:
<scripttype="py">import anycad_next as ac#在浏览器中直接建模</script>2. AI 辅助建模
# 自然语言生成建模代码ai.generate_code("创建一个带 6 个螺栓孔的法兰盘,外径 100mm,厚度 10mm")# 自动生成 PyScript 或 CLI 脚本3. 云端协同
# 多人协同建模with ac.Application.connect("cloud://team-project")as app:# 实时同步修改pass💡 总结
AnyCAD NEXT 提供了 PyScript 和 CLI 两种互补的自动化建模方式:
| 定位 | ||
| 优势 | ||
| 推荐 |
建议:
• 🎯 初学者:从 CLI 开始,快速上手 • 🎯 开发者:掌握 PyScript,发挥最大潜力 • 🎯 团队:混合使用,各取所长
无论您选择哪种方式,AnyCAD NEXT 都能帮助您实现高效的 CAD 自动化,释放创造力,提升工作效率!
夜雨聆风