Hi. I created a function to check if a block definition is created in the drawing. If so, the code is supposed to skip it and if not to create a new one. Its a quick and dirty version so a lot of things to be improved however it seems to work correctly as long as I run it on a single item. If I attempt to run in on more than one item it crashes. Any advices?
Please see my code:
# Load the Python Standard and DesignScript Libraries
import sys
import clr
import math
import datetime
# Add Assemblies for AutoCAD
clr.AddReference('AcMgd')
clr.AddReference('AcCoreMgd')
clr.AddReference('AcDbMgd')
# Import references from AutoCAD
from Autodesk.AutoCAD.Runtime import *
from Autodesk.AutoCAD.ApplicationServices import *
from Autodesk.AutoCAD.ApplicationServices.Core import *
from Autodesk.AutoCAD.EditorInput import *
from Autodesk.AutoCAD.DatabaseServices import *
from Autodesk.AutoCAD.Geometry import *
# Access the active AutoCAD document
adoc = Application.DocumentManager.MdiActiveDocument
editor = adoc.Editor
database = adoc.Database
# Initialize counter
outp = []
modelID = []
chkname = IN[0]
print('New run: ' + str(datetime.datetime.utcnow().isoformat()))
def checkandcreateblocdefs(blockdefinitionname):
blockdefid = None
#print(blockdefid)
out_stat = []
if 1 == 1:
# Start transaction
with adoc.LockDocument():
with database as db:
# Start transaction
with db.TransactionManager.StartTransaction() as t:
# Open the Block table for read
block_table = t.GetObject(db.BlockTableId, OpenMode.ForRead)
for elemID in block_table:
elem = t.GetObject(elemID, OpenMode.ForRead)
if elem.Name == blockdefinitionname:
blockdefid = elemID
print(blockdefid)
elemRefIds = elem.GetBlockReferenceIds(False, True)
elemRefIdsCount = len(elemRefIds)
out_stat.append("Found __" + elem.Name + "__ with number of occurances " + str(len(elemRefIds)))
##print ("to ten! " + elem.Name + " " + str(len(elemRefIds)))
break
##
##
if blockdefid == None:
newBTR = BlockTableRecord()
newBTR.Name = blockdefinitionname
block_table.UpgradeOpen()
block_table.Add(newBTR)
t.AddNewlyCreatedDBObject(newBTR, True)
out_stat.append("definition created__" + newBTR.Name + "__")
##
##
t.Commit()
pass
return out_stat
chkname = ["a","AeccArrow"]
if chkname != None:
for chknamee in chkname:
#a1=checkandcreateblocdefs(chknamee)
#outp.append(a1)
print(type(chknamee) is str)
print(type(chknamee))
print(chknamee)
outp.append(checkandcreateblocdefs(chknamee))
break
else:
outp.append("No input")
#a = checkandcreateblocdefs("a")
#b = checkandcreateblocdefs("AeccArrow")
OUT = outp