I am trying to make a plug-in that loads a menu with a simple print command attached to a button. I got two files:
- test_menu.py
import maya.cmds as cmds
import maya.mel as mel
def say_hello():
print('hello')
def menuui():
main_window = mel.eval("$retvalue = $gMainWindow;")
custom_menu = cmds.menu('test_menu', label='test_menu', parent=main_window, tearOff=True)
cmds.menuItem(label='say hello', command='say_hello()')
cmds.setParent( '..', menu=True )
menuui()
- test_plugin.py
import maya.cmds as cmds
from maya.api import OpenMaya
import os
maya_useNewAPI = True
def load_menu(script_path):
if os.path.isfile(script_path):
with open(script_path) as f:
exec(f.read(), globals())
def unload_menu():
cmds.deleteUI(cmds.menu('test_menu', e=True, deleteAllItems=True))
def initializePlugin(plugin):
plugin_fn = OpenMaya.MFnPlugin(plugin)
load_menu("C:/Users/Roger/Documents/maya/scripts/test_menu.py")
def uninitializePlugin(plugin):
plugin_fn = OpenMaya.MFnPlugin(plugin)
unload_menu()
When the test_menu.py is executed within the 'Script Editor' it works as expected. But, when executed as a plug-in it only loads the menu but when pressing the button it returns: # Error: NameError: file line 1: name 'say_hello' is not defined # .
It seems as if when loading the plugin maya executes it outside the scene?
The only workaround i've found. Which is quite horrible tbh is to add import test_menu before executing the command.
cmds.menuItem(label='say hello', command='import test_menu; say_hello()')
I would appreciate any help :)
The way I've dealt with custom plug-ins in Maya, is to use a module file.
In the Maya preferences folder, you need a
plug-insfolder as well as amodulesfolder (just create them if they don't exist).File structure
As an example, let's make a plug-in called
foo. Start by creating the following file structureEdit the files
foo.mod
foo.py
modules/menu.py
Note that the command argument uses a reference to the
print_commandand NOT a string'print_command()'. You can usepartialif you want to pass arguments.