Search code examples
pythonwindowspython-importimporterrormaya

Importing external Python-Scripts from Disk into Maya


Im trying to setup an Interface for calling the current version of the scipts in a certain Folder.

Im appending my personal script folder and try to import it as its told. Whenever I press the Button, the following Error Message appears:

Error: NameError: file line 1: name 'setVars' is not defined

I´ve tried numerous possible import techniques. But the Errors keep popping up.

I´ll attach the Interface Script and one of the scipts that are ment to be called.

Interface:

import maya.cmds as mc
import sys
import os
import importlib

FolderContent = []
SysPath = 'C:/Users/[Username]/Documents/maya/2019/scripts/Personal'
sys.path.append(SysPath)
print sys.path


for file in os.listdir(SysPath):
    if file.endswith(".py"):
        FolderContent.append(file)
        

def UI(FolderContent):    
    x = 0
    
    if mc.window("Run_Script", ex = True):
        mc.deleteUI("Run_Script")
        
    popUp = mc.window("Run_Script")
        
    mc.gridLayout(nc = 1, ch = 30, cw = 300)
    
    for i in FolderContent:
        ScriptName = FolderContent[x]
        mc.button(label = FolderContent[x], command = 'callFunc(\'%s\')' % (ScriptName), bgc = (0.25, 0.25, 0.25))
        x += 1
    
    mc.button(label = 'Cancel', command = 'close()', bgc = (0.92, 0.4, 0.4)) 
    
    mc.window(popUp, e = True, s = False, h = 50, w = 100)
    mc.showWindow()
UI(FolderContent)

def callFunc(ScriptName):
    ScriptName = ScriptName[0:-3]

    mymodule = importlib.import_module(ScriptName)
   
    
def close():
    mc.deleteUI("Run_Script")

Example Script to be called:

import maya.cmds as mc

mc.select(hi = True)
BaseChain = mc.ls(sl = True)
ChainLength = len(BaseChain) - 1

###################################################################################

if mc.window("SetVariables", ex = True):
    mc.deleteUI("SetVariables")
            
popUp = mc.window("SetVariables")
            
mc.gridLayout(nc = 2, ch = 30, cw = 200)

mc.text(label = "Side")
mc.textField("side")
mc.text(label = "Limb")
mc.textField("limb")
mc.text(label = "FK-Amount")
mc.textField("amount", fi = ChainLength)
      

cmd = 'setVars()'
close = 'closeWindow()'     
mc.button(label = "OK", command = cmd, bgc = (0.2, 0.92, 0.75))
mc.button(label = "Cancel", command = close, bgc = (0.92, 0.4, 0.4)) 

mc.window(popUp, e = True, s = False, h = 50, w = 100)
mc.showWindow()

###################################################################################

def createChains(side, limb, amount):
    mc.select(hi = True)
    BndChain = mc.ls(sl = True)
        
    x = 0
    for i in BndChain:
        mc.rename(BndChain[x], side + '_' + limb + '_BND_Chain_0' + str(x + 1))
        x += 1

    BndChain = mc.ls(sl = True)
    ChainLength = len(BndChain)

    mc.duplicate( n = side + '_' + limb + '_FK_Chain_01')
    FkChain = mc.ls(sl = True)

    mc.duplicate( n = side + '_' + limb + '_IK_Chain_01')
    IkChain = mc.ls(sl = True)

    parentChains(ChainLength, FkChain, IkChain, BndChain, side, limb, amount)

###################################################################################

def parentChains(ChainLength, FkChain, IkChain, BndChain, side, limb, amount):
    x = 0

    while x < ChainLength:
        mc.select(FkChain[x])
        mc.select(IkChain[x], add = True)
        mc.select(BndChain[x], add = True)
        
        mc.parentConstraint(mo = False)
        
        x += 1
    FKChainCtrl(ChainLength, FkChain, IkChain, BndChain, side, limb, amount)   

###################################################################################

def FKChainCtrl(ChainLength, FkChain, IkChain, BndChain, side, limb, amount):

    listLength = len(FkChain)
    invertedNumber = listLength - int(amount)
    doFK = listLength - invertedNumber

    x = 0
    Fk_ctrls = []

    while x < doFK:
        queryObj = FkChain[x]
        
        currCtrl = mc.circle(n = side + '_' + limb + '_' + 'FK' + '_' + 'CTRL' + '_01', nr = [1, 0, 0], sw = 180)[0]
        mc.curveRGBColor('translate.X', 1, 0, 1)
        Fk_ctrls.append(currCtrl)
        
        mc.parentConstraint(queryObj, currCtrl, mo = False)
    
        mc.select(cl = True)
        mc.select(queryObj)
        mc.select(currCtrl, add = True)
        mc.RemoveConstraintTarget()

        mc.select(cl = True)
        mc.select(currCtrl)
        sel = mc.ls(sl = True)[0]
        mc.FreezeTransformations(sel)

        mc.parentConstraint(currCtrl, queryObj, mo = True)

        if(x > 0):
            mc.parent(Fk_ctrls[-1], Fk_ctrls[-2])
        
        x += 1 
    
    mc.hide(FkChain)
    IKChainCtrl(IkChain, BndChain, side, limb)
    
################################################################################### 

def IKChainCtrl(IkChain, BndChain, side, limb):
   
    currHandle = mc.ikHandle(n = side + '_' + limb + '_IkHandle', sj = IkChain[0], ee = IkChain[-1])[0]
    mc.hide()
    currHandlePos = mc.xform(currHandle, q = True, t = True, ws = True)
    currCtrl = mc.circle(n = currHandle + '_CTRL', nr = [1, 0, 0], r = 1.5)
    
    # currCtrl = mc.curve(n = currHandle + '_CTRL', d = 1, p = [(-0.75, 0, 0), (-0.75, 0, 2.5), (-2.5, 0, 2.5), (0, 0, 6.25), (2.5, 0, 2.5), (0.75, 0, 2.5), (0.75, 0, 0), (0.75, 0, -2.5), (2.5, 0, -2.5), (0, 0, -6.25), (-2.5, 0, -2.5), (-0.75, 0, -2.5), (-0.75, 0, 0)])

    # mc.setAttr(currCtrl + '.overrideEnabled', 1)
    # mc.setAttr(currCtrl + '.overrideColor', 21)


    mc.select(IkChain[-2])
    mc.select(currCtrl, add = True)
    mc.parentConstraint(mo = False)
    
    mc.select(IkChain[-2])
    mc.select(currCtrl, add = True)
    
    sel = mc.ls(sl = True)
    mc.select(sel[0:-1], r = True)
    
    mc.RemoveConstraintTarget()
    
    mc.xform(currCtrl, t = [currHandlePos[0], currHandlePos[1], currHandlePos[2]])
    mc.select(currCtrl, r = True)
    mc.FreezeTransformations()
    # mc.select('makeNurbCircle3', d = True)
    mc.duplicate()
    
    mc.parentConstraint(currCtrl, currHandle, mo = True)
    mc.rename(side + '_' + limb + '_IkHandle_CTRL1', side + '_' + limb + '_Switch')
    mc.xform(s = [1.5, 1.5, 1.5])
    SwitchCtrl = mc.ls(sl = True)
    mc.pointConstraint(BndChain[-1], SwitchCtrl)
    
    currCtrl = mc.ls(sl = True)[0]
    mc.hide(IkChain)
    
    AddSwitchAttributes(currCtrl, side, limb)
    
###################################################################################   
    
def AddSwitchAttributes(currCtrl, side, limb):

    mc.addAttr(currCtrl, sn = 'FK', nn = 'FK', min = 0, max = 1, dv = 0, k = True, h = True)
    mc.addAttr(currCtrl, sn = 'IK', nn = 'IK', min = 0, max = 1, dv = 1, k = True, h = True)
    mc.addAttr(currCtrl, sn = 'Switch', nn = 'FK|IK Switch', min = 0, max = 1, dv = 1, k = True)

    mc.connectAttr(side + '_' + limb + '_Switch.FK', side + '_' + limb + '_FK_CTRL_01.visibility')
    mc.connectAttr(side + '_' + limb + '_Switch.IK', side + '_' + limb + '_IkHandle_CTRL.visibility')
    
    i = 1

    while i < ChainLength + 2:
    
        mc.setDrivenKeyframe(side + '_' + limb + '_BND_Chain_0' + str(i) + '_parentConstraint1.' +  side + '_' + limb + '_IK_Chain_0' + str(i) + 'W1', cd = side + '_' + limb + '_Switch.Switch', v = 1.0)
        mc.setDrivenKeyframe(side + '_' + limb + '_BND_Chain_0' + str(i) + '_parentConstraint1.' +  side + '_' + limb + '_FK_Chain_0' + str(i) + 'W0', cd = side + '_' + limb + '_Switch.Switch', v = 0.0)
        i += 1
    
    mc.setDrivenKeyframe(side + '_' + limb + '_Switch.IK', cd = side + '_' + limb + '_Switch.Switch', v = 1.0)
    mc.setDrivenKeyframe(side + '_' + limb + '_Switch.FK', cd = side + '_' + limb + '_Switch.Switch', v = 0.0)
    
    mc.setAttr(side + '_' + limb + '_Switch.Switch', 0)
    
    y = 1

    while y < ChainLength + 2:
    
        mc.setDrivenKeyframe(side + '_' + limb + '_BND_Chain_0' + str(y) + '_parentConstraint1.' + side + '_' + limb + '_IK_Chain_0' + str(y) + 'W1', cd = side + '_' + limb + '_Switch.Switch', v = 0.0)
        mc.setDrivenKeyframe(side + '_' + limb + '_BND_Chain_0' + str(y) + '_parentConstraint1.' + side + '_' + limb + '_FK_Chain_0' + str(y) + 'W0', cd = side + '_' + limb + '_Switch.Switch', v = 1.0)
        y += 1
    
    mc.setDrivenKeyframe(side + '_' + limb + '_Switch.IK', cd = side + '_' + limb + '_Switch.Switch', v = 0.0)
    mc.setDrivenKeyframe(side + '_' + limb + '_Switch.FK', cd = side + '_' + limb + '_Switch.Switch', v = 1.0)
    
    mc.setAttr(side + '_' + limb + '_Switch.Switch', 1) 
    
    mc.select(cl = True)
    
###################################################################################        

def setVars():
    side = mc.textField("side", q = True, tx = True)
    limb = mc.textField("limb", q = True, tx = True)
    amount = mc.textField("amount", q = True, tx = True)
    createChains(side, limb, amount)
    closeWindow()
  
###################################################################################

def closeWindow():
    mc.deleteUI("SetVariables")

Thank you for your help!


Solution

  • Okay, I tried it now and there are some problems. I suppose you executed your main script directly from within maya? Because if I put it into a module and load it, I get a similiar error that "close()" is not found as well as "callFunc()" is not found. Both have the same reason which can easily be solved by not using strings.

    In your main script, you can replace the "close()" in the button command with the same procedure as mentioned above:

    mc.button(label = 'Cancel', command = close, bgc = (0.92, 0.4, 0.4))
    

    Since the button command automatically adds an argument you will have an default argument to the close() command, something like close(dummyArg).

    The callFunc() is a little bit more complicated because you use an argument. This can be solved by partial e.g.:

    from functools import partial
    for value in FolderContent:
        mc.button(label = value, command = partial(callFunc, value), bgc = (0.25, 0.25, 0.25)) 
    

    The button call will add another boolean to the call, so that the callFunc will receive another argument which can be captured by adding another argument to the callFunc definition like callFunc(scriptName, value). This way your function object is used not a string. But now you have another problem because if you load the module the first time, you will get an error

    NameError: global name 'close' is not defined #

    That's because the function is not yet defined at the moment it us used, so you have to put the function definition at before the UI definition function. Now if your script is imported you will get similiar problems with functions defined by strings, but they can be solved the same way as in the main module.