有了前文的铺垫,本篇文章将介绍如何将一些常见的Tcl API转换为Python API的方式,以帮助大家更好地了解两者的功能实现,以及差异。
1:创建component
#### tcl
*createentity comps name="Component1"
#### Python
import hm
import hm.entities as ent
session = hm.Session()
model = hm.Model(session.get_all_models()[0])
comp1 = ent.Component(model)
comp1.name = "Component1"
2:添加节点
#### Tcl代码
*createnode 10.0 20.0 30.0 0
# Python代码
import hm
import hm.entities as ent
session = hm.Session()
model = hm.Model(session.get_all_models()[0])
nodeNew = ent.Node(model)
nodeNew.localcoordinates = [0,0,0]
3:定义材料
#### Tcl代码
*createentity mats name=Al
*setvalue mats id=1 cardimage="MAT1"
*setvalue mats id=1 STATUS=2 1=70000
*setvalue mats id=1 STATUS=2 3=0.3
*setvalue mats id=1 STATUS=2 4=2700
#### Python代码
import hm
import hm.entities as ent
session = hm.Session()
model = hm.Model(session.get_all_models()[0])
mat1 = ent.Material(model)
mat1.name = "Al"
mat1.cardimage = "MAT1"
mat1.E = 7e04
mat1.Nu = 0.3
mat1.Rho = 2700
4:设置属性
#### Tcl代码
*createentity props name=property
*setvalue props id=1 cardimage=PSHELL
*setvalue props id=1 STATUS=2 95=1
*setvalue props id=1 100201={mats 1}
#### Python代码
import hm
import hm.entities as ent
session = hm.Session()
model = hm.Model(session.get_all_models()[0])
prop1 = ent.Property(model)
prop1.name = "property"
prop1.cardimage = "PSHELL"
prop1.PSHELL_T = 1.0
mat1 = hm.Collection(model, ent.Material)
for mat in mat1:
mat_id = mat
break
prop1.materialid = mat_id
5、交互选择
#### Tcl
*createmarkpanel elem 1 "select elem"
*maskentitymark elements 1 0
###Python
import hm
import hm.entities as ent
model = hm.Model()
col_elem = hm.CollectionByInteractiveSelection(model, ent.Element)
for elem in col_elem:
model.hideentity(elem)
6、结果查询
### tcl
*createmarkpanel property 1 ""
foreach temp [hm_getmark property 1] {
puts [list [hm_getvalue property id=$temp dataname=name] \
[hm_getvalue property id=$temp dataname=materialid] \
[hm_getvalue property id=$temp dataname=95]]
}
### python
import hm
import hm.entities as ent
import prettytable as pt
def main():
model = hm.Model()
prop_data = list()
props = hm.Collection(model, ent.Property)
for p in props:
prop_name = p.name
prop_id = p.id
prop_cardimage = p.cardimage
if prop_cardimage == "PSHELL":
prop_thickness = p.PSHELL_T
else:
prop_thickness = ""
if p.materialid:
mat = p.materialid
mat_name = mat.name
mat_id = mat.id
mat_cardimage = mat.cardimage
else:
mat_name = "-"
mat_id = "-"
mat_cardimage = "-"
prop_data.append(
[
prop_name,
prop_id,
prop_cardimage,
prop_thickness,
mat_name,
mat_id,
mat_cardimage,
]
)
tab = pt.PrettyTable(
[
"Prop Name",
"Prop ID",
"Prop Cardimage",
"Prop Thickness",
"Mat Name",
"Mat ID",
"Mat Cardimage",
]
)
tab.add_rows(prop_data)
print(tab)
if __name__ == "__main__":
main()
通过上述几个常见的Tcl API转换示例,相信大家已经对如何将HyperWork 2024中的Tcl代码过度到Python代码有了初步的了解,更多细节还是在帮助文挡里边。
Python语言在二次开发中的强大功能和简洁语法,将大大提高开发效率和代码质量,两者之间还是存在差异,例如Collection返回的就是迭代器,写习惯就好了。
在实际项目中,可以根据需要进一步扩展和深入使用Python API。就自己去探索了。
昨天拍到的奇观,天空惊现八个排列整齐的🛸🛸🛸🛸🛸🛸🛸🛸