Print Selected Objects

Create some objects, lights, polygons, whatever. Select some objects and run this script in the maya python editor. It prints out the list of objects selected.

download : printSelectedObjectsAPI.py

 

Here is the full program in python:

 
import maya.OpenMaya as OM
#Creates an empty selection list.
LIST = OM.MSelectionList()
#Assign active selections to a selection list.
OM.MGlobal_getActiveSelectionList(LIST)
     
for i in range(0 ,LIST.length()):
  #Creates a pointer for an object.
  obj = OM.MObject()
  #Get a handle for the dependency node of the given element of the selection list
  #assign to pointer.
  LIST.getDependNode(i,obj)
     
  #MFnDependencyNode allows the creation and manipulation of dependency graph nodes
  #Attaches a function set to the object pointer
  node=OM.MFnDependencyNode(obj)
  #This is one of the nodes to print
  print (node.name()+"\n")
     
 

In MEL this program would be:

$r = `ls-sl`;

for ($i in $r) {

print $i;

}

Python script without Comments:

import maya.OpenMaya as OM
LIST = OM.MSelectionList()
OM.MGlobal_getActiveSelectionList(LIST)
for i in range(0 ,LIST.length()):
  obj = OM.MObject()
  LIST.getDependNode(i,obj)
  node=OM.MFnDependencyNode(obj)
  print (node.name()+"\n")
     

One interesting thing about this script is that I used

help (OM.MGlobal)

in the script editor and it returned a list of the methods of the class MGlobal (and such), and it had me create

OM.MGlobal_getActiveSelectionList(LIST) to fill LIST with the objects selected.

And later using the regular API reference, it is indexed as

OM.MGlobal.getActiveSelectionList(LIST).

Just a heads up that not all code is tied down to absolutes. And of course both work in this case, but a "_" is not synonomous with a ".". I probably will stick with "." everywhere to keep things looking normal.