Python code for selection

i was trying to get the element ID of the selected elements. but when write the code below code is not working. which library I supposed to import to work it properly.

uidoc = commandData.Application.ActiveUIDocument

import clr
clr.AddReference('RevitServices')
from RevitServices.Persistence import DocumentManager

doc = DocumentManager.Instance.CurrentDBDocument
uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument

Will get you the active document. You’ll need to supply more details about what you’re trying to achieve for the rest

thank you, is there any document for the library

The UIDocument has a Selection property. Referencing the Selection class, you can use the GetElementIds method to get the element ids of the current selection.

I created below code to pick the object from screen. but it is not working.
import clr
clr.AddReference(‘ProtoGeometry’)
clr.AddReference(‘RevitServices’)
from Autodesk.DesignScript.Geometry import *
from RevitServices.Persistence import DocumentManager
from RevitServices.Persistence import *
doc = DocumentManager.Instance.CurrentDBDocument

uiapp = DocumentManager.Instance.CurrentUIApplication
uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument
app = uiapp.Application

clr.AddReference(‘RevitNodes’)
import Revit
clr.ImportExtensions(Revit.Elements)

clr.AddReference(‘RevitAPI’)

from Autodesk.Revit.DB import *
from Autodesk.Revit.DB import APIObject
from Autodesk.Revit.DB.Mechanical import *
clr.AddReference(“RevitAPIUI”)
from Autodesk.Revit.UI import *
import Autodesk
ref = Autodesk.Revit.DB.Reference
sel = uidoc.Selection
po = sel.PickObject
po1 = po.Targets
#selid = sel.GetElementIds().Count
selob = sel.PickObject(ObjectType.Element)

OUT = selob

Once you have the uidoc, you can get the ids of the elements as @cgartland says, and from there the elements themselves by querying the doc:

ids = uidoc.Selection.GetElementIds()
elems = []
for id in ids:
	try:
		elems.append(doc.GetElement(id))
	except:
		elems.append('Element retrieval failed')

OUT = elems

revitapidocs: Selection.GetElementIds
revitapidocs: Document.GetElement

1 Like