PYREVIT
-2023-

pyRevit Script Typologies

Templates to start from based on your script's purpose.

Metadata for scripts:

__title__ = 'Title of script'
__author__ = 'Thomas Goodwin'
__helpurl__ = "https://www.thomasfgoodwin.com"
__min_revit_ver__= 2016
__max_revit_ver__ = 2023
__beta__ = True

Collect all instances of a category and iterate over a property of those instances

from Autodesk.Revit import DB


doc = __revit__.ActiveUIDocument.Document


#Collect all instances
instance_collector = DB.FilteredElementCollector(doc)\
                   .OfCategory(DB.BuiltInCategory.OST_Walls)\
                   .WhereElementIsNotElementType()

# Iterate over them
total_volume = 0.0

for instance in instance_collector:
    parameter = wall.Parameter[DB.BuiltInParameter.HOST_VOLUME_COMPUTED]
    if parameter:
        total_volume = total_volume + parameter.AsDouble()

# Output
print("Total Volume of all walls in model is: {}".format(total_volume))

Edit the value of a parameter for selected objects:

from Autodesk.Revit import DB

parameter_name = '<parameter name>'
value = 'value'
__title__= f'Edit {parameter_name}'

doc = __revit__.ActiveUIDocument.Document
selection = __revit__.ActiveUIDocument.Selection
selected_items = [doc.GetElement(x) for x in selection.GetElementIds()]

# Create a Revit transaction
t = DB.Transaction(doc, __title__)
t.Start()
# Add change to transaction for each selected item
for item in selected_items
    parameter = item.LookupParameter(parameter_name)
    parameter.Set(value)
# Commit the transaction to Revit
t.Commit()

Dump document-specific information to a JSON file

from Autodesk.Revit import DB
from pyrevit import script
import json

doc = __revit__.ActiveUIDocument.Document
selection = __revit__.ActiveUIDocument.Selection

selection_ids = [x for x in selection.GetElementIds()]

data = {}
for item_id in selection_ids:
    element = doc.GetElement(item_id)
    key = element.UniqueId
    parameter = '<parameter name>'
    value = element.LookupParameter(parameter)
    data[key] = value

filename = script.get_document_data_file('<file name>', 'json', add_cmd_name=False)
with open(path, 'w') as f:
         json.dump(data, f)

-Published 9 am Thu, Feb 16 2023-