Morten
Morten

Reputation: 497

Maya's nameCommand not able to call functions

I'm having an issue with calling functions from nameCommand's in Maya used with hotkeys. I can't tell if it's a Maya or Python issue.

The following MEL works as expected

proc myTest() {
    print("test");
}

nameCommand -ann "test" -command "myTest()" testCommand;
hotkey -k "l" -name "testCommand";

However, translated to Python, I get an error

import maya.cmds as cmds

def myPythonTest():
    print("myPythonTest")

cmds.nameCommand("pythonTestCommand", ann="pythonTest", command="myPythonTest()", sourceType="python")
cmds.hotkey(k="l", name="pythonTestCommand")

// Error: line 1: Cannot find procedure "myPythonTest".

Is it the wrong way to call functions in Python, or is something else going on? I've noticed that the parentheses are being stripped, and calling the function with myPythonTest() from the script editor works as expected.

Upvotes: 0

Views: 1462

Answers (2)

Arubertoson
Arubertoson

Reputation: 38

To expand on the previous answer I believe Achayan is correct in the assesment that sourceType seems to be broken.

If you want to be able to pass python code to a nameCommand you need to first create a runTimeCommand

def testy():
    print('hello')

# There is no way to edit a runtime command so we need to check if it
# exists and then remove it if it does.
my_command_name = 'my_runtime_command'
if cmds.runTimeCommand(my_command_name, q=True, exists=True):
    cmds.runTimeCommand(my_command_name, e=True, delete=True)

cmds.runTimeCommand(
    my_command_name, 
    ann='My Command', 
    category='User', 
    command='testy()', 
    commandLanguage='python'
    )
cmds.nameCommand('my_name_command', ann='My Command', command=my_command_name)
cmds.hotkey(k='1', name='my_name_command')

As you see you don't need to provide a sourceType, the nameCommand is just a string representation of the runtimecommand and will just execute the given runTimeCommand. So the real place to specify execution language is in the commandLanguage flag of the runTimeCommand.

Upvotes: 0

Achayan
Achayan

Reputation: 5895

cmds.nameCommand("pythonTestCommand", ann="pythonTest", command='python("myPythonTest()")', sourceType="python")
cmds.hotkey(k="l", name="pythonTestCommand")

Should work

Upvotes: 2

Related Questions