导入相关模块
from pyautocad import Autocad, APoint
创建AutoCAD应用程序或连接到已经运行的应用程序:
acad = Autocad(create_if_not_exists=True)
# 在CAD命令行输出内容
acad.prompt("Hello, Autocad from Python\n")
# 输出当前图形文件的名称
print(acad.doc.Name)
在文档中添加对象:
p1 = APoint(0, 0)
p2 = APoint(50, 25)
for i in range(5):
text = acad.model.AddText(u'Hi %s!' % i, p1, 2.5)
acad.model.AddLine(p1, p2)
acad.model.AddCircle(p1, 10)
p1.y += 10
迭代文档中的Texts, Lines和Circles对象:
for obj in acad.iter_objects():
print(obj.ObjectName)
for text in acad.iter_objects('Text'):
print(text.TextString, text.InsertionPoint)
for obj in acad.iter_objects(['Text', 'Line']):
print(obj.ObjectName)
在一定条件下找到第一个对象:
def text_contains_3(text_obj):
return '3' in text_obj.TextString
text = acad.find_one('Text', predicate=text_contains_3)
print(text.TextString)
通过ACAD查找对象并修改属性:
from pyautocad import ACAD
for text in acad.iter_objects('Text'):
old_insertion_point = APoint(text.InsertionPoint)
text.Alignment = ACAD.acAlignmentRight
text.TextAlignmentPoint = old_insertion_point
更改对象位置:
for line in acad.iter_objects('Line'):
p1 = APoint(line.StartPoint)
line.EndPoint = p1 - APoint(20, 0)
添加对象并保存到EXCEL中:
from pyautocad import Autocad, APoint
from pyautocad.contrib.tables import Table
acad = Autocad()
p1 = APoint(0, 0)
for i in range(5):
obj = acad.model.AddText(u'Hi %s!' % i, p1, 2.5)
p1.y += 10
table = Table()
for obj in acad.iter_objects('Text'):
x, y, z = obj.InsertionPoint
table.writerow([obj.TextString, x, y, z])
table.save('C:/Users/liuzhi/Desktop/data.xls', 'xls')
提高AutoCAD表格操作的速度:
table = acad.model.AddTable(pos, rows, columns, row_height, col_width)
with suppressed_regeneration_of(table):
table.SetAlignment(ACAD.acDataRow, ACAD.acMiddleCenter)
for row in range(rows):
for col in range(columns):
table.SetText(row, col, '%s %s' % (row, col))
class pyautocad.api.Autocad(create_if_not_exists=False, visible=True)
参数:
创建if_NOT_存在-如果AutoCAD不运行,那么新的实例化将被装箱
可见-如果是True(默认),新的AutoCAD实例将是可见的。
prompt(文本)
在控制台和AutoCAD提示符
get_selection(Text=“SelectObjects”)
要求用户选择对象
pyautocad.types.distance(P1, P2)
返回两点之间的距离P1和P2
pyautocad.types.aDouble(*seq)
回报array.array为传递到AutoCAD的双倍代码(‘d’代码),对于3D点使用APoint相反。
pyautocad.types.aInt(*seq)
回报array.array用于传递到AutoCAD的INTS(‘l’代码)
pyautocad.types.aShort(*seq)
回报array.array传递到AutoCAD的简写(h‘代码)