-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFreeCADspreadsheet_example.py
More file actions
163 lines (127 loc) · 5.63 KB
/
Copy pathFreeCADspreadsheet_example.py
File metadata and controls
163 lines (127 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import subprocess
import os
import sys
import tkinter as tk
from tkinter import filedialog
import textwrap # <--- 新增:用于清除多行字符串的缩进
# --- 1. 设置路径 ---
fc_cmd = r"C:\Users\lichengd\AppData\Local\Programs\FreeCAD 1.0\bin\freecadcmd.exe" # no GUI
# fc_cmd = r"C:\Users\lichengd\AppData\Local\Programs\FreeCAD 1.0\bin\freecad.exe" # with GUI
# cad_file = r"C:\Users\lichengd\OneDrive - Oregon State University\1. PhD\Chiller\automation\Chiller_auto_Python\CAD_files\Coldplate_spreadsheet.FCStd"
# cad_file = r"C:\Users\lichengd\OneDrive - Oregon State University\1. PhD\Chiller\automation\Chiller_auto_Python\CAD_files\Coldplate_spreadsheet.FCStd"
# cad_file = r"C:\Users\lichengd\OneDrive - Oregon State University\1. PhD\Chiller\automation\Chiller_auto_Python\CAD_files\Cube_spreadsheet.FCStd"
cad_file = r"C:\Users\lichengd\OneDrive - Oregon State University\1. PhD\Chiller\automation\Chiller_auto_Python\CAD_files\Box_hole_Spreadsheet.FCStd"
# # --- 2. 交互式选择文件 (新增功能) ---
# print("正在打开文件选择窗口...")
# # 初始化 tkinter (隐藏主窗口)
# root = tk.Tk()
# root.withdraw()
# # 确保窗口弹到最前面
# root.attributes('-topmost', True)
# # 弹出文件选择框
# cad_file = filedialog.askopenfilename(
# title="请选择 FreeCAD 模型文件",
# filetypes=[("FreeCAD Files", "*.FCStd"), ("All Files", "*.*")],
# initialdir=r"C:\Users\lichengd\OneDrive - Oregon State University\1. PhD\Chiller\automation\Chiller_auto_Python\CAD_files" # 可选:设置默认打开文件夹
# )
# # 检查用户是否取消了选择
# if not cad_file:
# print("❌ 用户取消了选择,程序退出。")
# sys.exit(0)
# print(f"✅ 已选择文件: {cad_file}")
# # Step 2: 自动生成导出路径 (同文件夹,同名,后缀改.step)
# # os.path.splitext 分离文件名和扩展名
# step_file = "Export_" + os.path.splitext(cad_file)[0] + ".step"
# print(f"📂 自动设置导出目标: {step_file}")
# # -------------- 输出路径和CAD名字 -----------------
# 1. 获取文件夹路径
dir_name = os.path.dirname(cad_file)
# 2. 获取文件名(不带后缀)
base_name = os.path.splitext(os.path.basename(cad_file))[0]
# 3. 拼接新路径: 文件夹 + "Export_" + 文件名 + ".step"
step_file = os.path.join(dir_name, "Export_" + base_name + ".step")
# ---- table of parameters -----
# result of Optimization will change the values here
cube_length = 70
cube_width = 50
cube_height = 100
hole_x = 5
hole_y = 6
hole_d = 7
params_to_update = {"length":cube_length,
"width":cube_width,
"height":cube_height,
"hole_x":hole_x,
"hole_y":hole_y,
"hole_d":hole_d,}
# --- path check for FreeCAD ---
if not os.path.exists(fc_cmd):
print(f"❌ error: unable to fine FreeCAD: {fc_cmd}")
sys.exit(1)
# --- 2. prepare worker code for FreeCAD to excute ---
# In Python 3.11, you cannot write backslashes inside the curly braces {} of an f-string.
# Therefore, need to process the path format correctly externally (replace \ with /).
cad_file_fixed = cad_file.replace('\\', '/')
step_file_fixed = step_file.replace('\\', '/')
# worker—_code will be pass in FreeCAD, and runned by FreeCAD's python console
worker_code = f"""
import FreeCAD
import Import
print(">> FreeCAD : starting dimesnion modification...")
try:
# 1. Open doc
doc = FreeCAD.openDocument(r"{cad_file_fixed}")
# 2. obtain spreadsheet
if hasattr(doc, "Spreadsheet"):
sheet = doc.Spreadsheet
print(f">> Find table: {{sheet.Label}} (internal ID: {{sheet.Name}})")
# 3. modify in batch
# params is passed by the dictionary - params_to_update
params = {params_to_update}
for param_name, new_value in params.items():
print(f">> modifying {{param_name}} to {{new_value}} ...")
# try every params
try:
sheet.set(param_name, str(new_value))
except Exception as e:
print(f" ⚠️ warning: fail to set {{param_name}},the parameter's name incorrect。error: {{e}}")
# 4. compute and save
doc.recompute()
doc.save()
print(">> FreeCAD: all changes completed, saving file")
else:
print(">> ❌ error: can't find object named as 'Spreadsheet'")
# 3. Export STEP
print("exporting .STEP file")
output_step = r"{step_file_fixed}"
body_obj = doc.getObject("Body")
if body_obj is not None:
Import.export([body_obj], output_step)
print(f">> export to: {{output_step}}")
else:
print(">> Fail: can't find 'Body' ")
# debug:list all the name in the CAD file
print(">> list all the name in CAD: ", [o.Name for o in doc.Objects])
except Exception as e:
print(f">> FreeCAD error: {{e}}")
"""
worker_code = textwrap.dedent(worker_code)
temp_script = "temp_task.py"
with open(temp_script, "w", encoding="utf-8") as f:
f.write(worker_code)
print(f" FreeCAD modify CAD file: {os.path.basename(cad_file)} ...")
try:
subprocess.run([fc_cmd, temp_script], check=True)
except subprocess.CalledProcessError:
print("\n❌ FreeCAD error, check info above")
except PermissionError:
print("\n⚠️ Administration error, try Shell mode ...")
subprocess.run(f'"{fc_cmd}" "{temp_script}"', shell=True, check=True)
except Exception as e:
print(f"\n❌ scripts error: {e}")
finally:
if os.path.exists(temp_script):
try: os.remove(temp_script)
except: pass
success_message = f"modification completed, file saved to: {os.path.basename(step_file)}"
print(success_message)