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 :)
horriblebut the normal solution with python if you cannot import your menu script into the plugin script. You wrote a python module and then you import it and create your menu. I'd rather impor in your plugin script and call it from there. Your first way to load a fiel and run it with the exec() command is a very unusual way.