[maya] maya python API equivalent to cmds.ls (sl=1)[0]

Hi,

something completely undocumented in the internet, so let’s put it here for future reference.

how would you write this in maya python API?
And I mean the simplest possible solution please.

currSel = cmds.ls (sl=1)[0]

thank you,
Bastian

Sorry, do you mean in OpenMaya? I’m confused…

BTW, I found this previous thread if so:


# Python API 1.0
import maya.OpenMaya as om
sel = om.MSelectionList()
om.MGlobal.getActiveSelectionList(sel)
names = []
sel.getSelectionStrings(names)
for name in names:
    print(name)

# Python API 2.0
import maya.api.OpenMaya as om2
sel = om2.MGlobal.getActiveSelectionList()
for name in sel.getSelectionStrings():
    print(name)

In straight up Maya Python it’s this

currSel = cmds.ls (sl=True)[0]

assuming you have imported maya.cmds as cmds

… although there’s no particular benefit to using the API if all you want is the strings… You typically want the selection as either mObjects (so you can attach function sets) or MDagPaths (so you can do things like renames while hanging on to the object).

Agreed, but getting the strings was the easiest way to show that it actually returned the same info as cmds.ls

just trying to get OP on board :slight_smile:

Hi,

actually great! Thank you, yes indeed I will use the pointer, but now I know how to receive a string aswell.
Since I need to update the information to the user inside a pySide interface.

thanks for the help, I’ll be brave now and read the whole API 2.0 documentation.