def _languageExecute(self): lines = self.data.splitlines() # if there is a prefix, add it to the start of each line # if len(self.server.prefix) > 0 : newLines = [] for _line in lines : newLines.append( self.server.prefix + ' "' + cmds.encodeString(_line) + ' "' ) lines = newLines self.data = '\n'.join( newLines ) outp = None if len(lines) == 1: try: # first try evaluating it as an expression so we can get the result outp = eval(self.data) except Exception: pass if outp is None: # more than one line, or failed to eval # exec everything instead try: exec self.data except Exception,ex: outp = ex
def melPrint(strToPrint): ''' this dumb looking method routes a print through the mel print command instead of the python print statement. this is useful because it seems the script line in the main maya UI doesn't echo data printed to the python.stdout. so if you want to communicate via this script line from python scripts, you need to print using this method ''' try: melEval('''print "%s\\n";''' % cmd.encodeString(str(strToPrint))) except RuntimeError: #if encodeString fails, bail... pass
def melPrint( strToPrint ): ''' this dumb looking method routes a print through the mel print command instead of the python print statement. this is useful because it seems the script line in the main maya UI doesn't echo data printed to the python.stdout. so if you want to communicate via this script line from python scripts, you need to print using this method ''' try: melEval('''print "%s\\n";''' % cmd.encodeString(str(strToPrint))) except RuntimeError: #if encodeString fails, bail... pass
def pyArgToMelArg(arg): #given a python arg, this method will attempt to convert it to a mel arg string if isinstance(arg, basestring): return '"%s"' % cmd.encodeString(arg) #if the object is iterable then turn it into a mel array string elif hasattr(arg, '__iter__'): return '{%s}' % ','.join(map(pyArgToMelArg, arg)) #either lower case bools or ints for mel please... elif isinstance(arg, bool): return str(arg).lower() #otherwise try converting the sucka to a string directly return unicode(arg)
def _languageExecute(self): writer = StringIO.StringIO() # if there is a prefix, add it to the start of each line # if len(self.server.prefix) > 0: newLines = [] for line in self.data.split('\n'): newLines.append(self.server.prefix + ' "' + cmds.encodeString(line) + '";') self.data = '\n'.join(newLines) if not self.server.sendResults: try: mel.eval(self.data) writer.write( self.resp_term ) except RuntimeError,ex: writer.write(unicode(ex) + self.resp_term)
def dpaf_layerRenderableTracker(self, layerOldName): global dpaf_unRenderableLayers try: tmp_undoInfo = cmds.undoInfo(q= 1, un= 1) layer = tmp_undoInfo.split()[-2].split('"')[1] value = tmp_undoInfo.split()[-1].split('"')[1] # store the undoInfo into Mel global for other procedure use mel.eval('global string $tmp_undoInfo = "' + cmds.encodeString(tmp_undoInfo) + '";') except: try: # try to load Mel global for undoInfo, if undoInfo has been flushed by other procedure tmp_undoInfo = mel.eval('$tmp = $tmp_undoInfo;') layer = tmp_undoInfo.split()[-2].split('"')[1] value = tmp_undoInfo.split()[-1].split('"')[1] except: layer = 'defaultRenderLayer' if cmds.optionMenu('af_layerMenu', q= 1, v= 1) == 'masterLayer' else cmds.optionMenu('af_layerMenu', q= 1, v= 1) value = cmds.getAttr(layer + '.renderable') if 'af_layerMenuItem_' + layer in cmds.optionMenu('af_layerMenu', q=1, ils= 1): cmds.deleteUI('af_layerMenuItem_' + layer) if cmds.optionMenu('af_layerMenu', q= 1, ni= 1) == 0: cmds.menuItem('af_layerMenuItem_NoRenderableLayer', l= 'No Renderable Layer', p= 'af_layerMenu') cmds.optionMenu('af_layerMenu', e= 1, en= 0) if int(value): if cmds.optionMenu('af_layerMenu', q= 1, v= 1) == 'No Renderable Layer': cmds.deleteUI('af_layerMenuItem_NoRenderableLayer') cmds.optionMenu('af_layerMenu', e= 1, en= 1) if layer in dpaf_unRenderableLayers: dpaf_unRenderableLayers.remove(layer) cmds.menuItem('af_layerMenuItem_' + layer, l= layer if layer != 'defaultRenderLayer' else 'masterLayer', p= 'af_layerMenu') if layer != 'defaultRenderLayer': cmds.scriptJob(ro= 1, ac= [layer + '.renderable', partial(self.dpaf_layerRenderableTracker, layer)], p= 'af_layerMenuItem_' + layer) cmds.scriptJob(nodeNameChanged= [layer, partial(self.dpaf_layerReNameTracker, layer)], p= 'af_layerMenuItem_' + layer) if layer == cmds.editRenderLayerGlobals(q= 1, currentRenderLayer= 1): cmds.optionMenu('af_layerMenu', e= 1, v= layer if layer != 'defaultRenderLayer' else 'masterLayer') else: cmds.deleteUI('af_layerMenuItem_' + layerOldName) if layer not in dpaf_unRenderableLayers: dpaf_unRenderableLayers.append(layer) if layer != 'defaultRenderLayer': cmds.scriptJob(ro= 1, ac= [layer + '.renderable', partial(self.dpaf_layerRenderableTracker, layer)], p= 'cgru_afanasy_wnd') if cmds.optionMenu('af_layerMenu', q= 1, ni= 1) == 0: cmds.menuItem('af_layerMenuItem_NoRenderableLayer', l= 'No Renderable Layer', p= 'af_layerMenu') cmds.optionMenu('af_layerMenu', e= 1, en= 0) self.dpaf_layerMenuSync()
def generateScript(): sel=mc.ls("*.zenMuscleInputs",o=True,sl=True) if not isIterable(sel) or len(sel)==0: sel=mc.ls("*.zenMuscleInputs",o=True) if not isIterable(sel): raise('You must select one or more muscles or Muscle Handle from which to generate creation scripts.') returnVal='' completed=[] for m in sel: myMuscle=Muscle(m) if myMuscle.Muscle not in completed: returnVal+=myMuscle.generateScript() completed.append(myMuscle.Muscle) if('opposite' in myMuscle.__dict__): completed.append(myMuscle.opposite.Muscle) if len(returnVal)>0: returnVal='import maya.mel as mel\nmel.eval("source zenTools")\nimport zen\n'+returnVal mel.eval('zenDisplayText("Muscle Script","'+mc.encodeString(returnVal)+'")') return returnVal
def pythonToMel(arg): # type: (str) -> str """ convert a python object to a string representing an equivalent value in mel iterables are flattened. mapping types like dictionaries have their key value pairs flattened: { key1 : val1, key2 : val2 } -- > ( key1, val1, key2, val2 ) """ if arg is None: return '' if arg is True or arg is False: return str(arg).lower() if util.isNumeric(arg): return str(arg) if isinstance(arg, datatypes.Vector): return '<<%f,%f,%f>>' % (arg[0], arg[1], arg[2]) if util.isIterable(arg): if isinstance(arg, Mapping): arg = list(_flatten(arg.items())) else: arg = list(_flatten(arg)) forceString = False for each in arg: if not util.isNumeric(each): forceString = True break if forceString: newargs = ['"%s"' % x for x in arg] else: newargs = [str(x) for x in arg] return '{%s}' % ','.join(newargs) # in order for PyNodes to get wrapped in quotes we have to treat special # cases first, we cannot simply test if arg is an instance of basestring # because PyNodes are not return '"%s"' % cmds.encodeString(str(arg))
def melEncode(arg): if isinstance(arg,basestring): return '"'+mc.encodeString(arg)+'"' elif isIterable(arg): returnVal='{' for i in range(0,len(arg)): if(isIterable(arg[i])): returnVal+='"' for n in range(0,len(arg[i])): returnVal+=str(arg[i][n]) if n<len(arg[i])-1 and len(str(arg[i][n]))>0: returnVal+=',' returnVal+='"' else: returnVal+=melEncode(arg[i]) if i<len(arg)-1 and len(str(arg[i]))>0: returnVal+=',' returnVal+='}' return returnVal return unicode(arg)
def prepMelCommand(commandString): return cmds.encodeString(commandString).replace("\\\"", "\"")
def prepMelCommand(commandString): return cmds.encodeString(commandString).replace("\\\"","\"")
def boCmdEncode(cmd): return cmds.encodeString(cmd).replace("\\\"", "\"")
OpenMaya.MCommandMessage.kError: 'Error: ', OpenMaya.MCommandMessage.kResult: 'Result: ' }[messageType] + nativeMsg if sourceType == kMel: convertedMsg = '# %s #\n' % nativeMsg nativeMsg = '// %s //\n' % nativeMsg else: nativeMsg = '# %s #\n' % nativeMsg except KeyError: pass nativeMsg = encodeString(nativeMsg) if convertedMsg is not None: convertedMsg = encodeString(convertedMsg) #outputFile = open( '/var/tmp/commandOutput', 'a') #outputFile.write( '---------\n%s %s\n' % ( convertedMsg, sourceType ) ) # outputFile.close() line = [messageType, sourceType, nativeMsg, convertedMsg] allHistory.append(line) # if messageType == OpenMaya.MCommandMessage.kError : # and 'Syntax error' in nativeMsg: # return for reporter in reporters.values():
def pythonToMel(arg): if isinstance(arg,basestring): return u'"%s"' % cmds.encodeString(arg) elif isIterable(arg): return u'{%s}' % ','.join( map( pythonToMel, arg) ) return unicode(arg)
def cmdCallback(nativeMsg, messageType, data): global callbackState #outputFile = open( '/var/tmp/commandOutput', 'a') #outputFile.write( '============\n%s\n%s %s, length %s \n' % (nativeMsg, messageType, callbackState, len(nativeMsg)) ) # outputFile.close() if callbackState == 'ignoreCommand': callbackState = 'ignoreResult' return elif callbackState == 'ignoreResult': callbackState = 'normal' return global sourceType global allHistory syntaxError = False convertedMsg = None # Command History if messageType == OpenMaya.MCommandMessage.kHistory: callbackState = 'normal' # if nativeMsg.rfind(';') == len(nativeMsg)-2 : # and len(nativeMsg) >= 2: if nativeMsg.endswith(';\n'): # and len(nativeMsg) >= 2: sourceType = kMel try: #convertedMsg = mel2py.mel2pyStr( nativeMsg ) convertedMsg = mparser.parse(nativeMsg) except Exception as msg: syntaxError = True pass else: sourceType = kPython # Display - unaltered strings, such as that printed by the print command elif messageType == OpenMaya.MCommandMessage.kDisplay and ( nativeMsg.endswith(';\n') or nativeMsg.startswith('//')): try: #convertedMsg = mel2py.mel2pyStr( nativeMsg ) convertedMsg = mparser.parse(nativeMsg) except Exception as msg: pass else: try: nativeMsg = { # OpenMaya.MCommandMessage.kDisplay: 'Output', OpenMaya.MCommandMessage.kInfo: '', OpenMaya.MCommandMessage.kWarning: 'Warning: ', OpenMaya.MCommandMessage.kError: 'Error: ', OpenMaya.MCommandMessage.kResult: 'Result: ' }[messageType] + nativeMsg if sourceType == kMel: convertedMsg = '# %s #\n' % nativeMsg nativeMsg = '// %s //\n' % nativeMsg else: nativeMsg = '# %s #\n' % nativeMsg except KeyError: pass nativeMsg = encodeString(nativeMsg) if convertedMsg is not None: convertedMsg = encodeString(convertedMsg) #outputFile = open( '/var/tmp/commandOutput', 'a') #outputFile.write( '---------\n%s %s\n' % ( convertedMsg, sourceType ) ) # outputFile.close() line = [messageType, sourceType, nativeMsg, convertedMsg] allHistory.append(line) # if messageType == OpenMaya.MCommandMessage.kError : # and 'Syntax error' in nativeMsg: # return for reporter in reporters.values(): reporter.appendHistory(line) if syntaxError: callbackState = 'syntax_error'
OpenMaya.MCommandMessage.kInfo: '', OpenMaya.MCommandMessage.kWarning: 'Warning: ', OpenMaya.MCommandMessage.kError: 'Error: ', OpenMaya.MCommandMessage.kResult: 'Result: ' }[ messageType ] + nativeMsg if sourceType == kMel: convertedMsg = '# %s #\n' % nativeMsg nativeMsg = '// %s //\n' % nativeMsg else: nativeMsg = '# %s #\n' % nativeMsg except KeyError: pass nativeMsg = encodeString( nativeMsg ) if convertedMsg is not None: convertedMsg = encodeString( convertedMsg ) #outputFile = open( '/var/tmp/commandOutput', 'a') #outputFile.write( '---------\n%s %s\n' % ( convertedMsg, sourceType ) ) #outputFile.close() line = [ messageType, sourceType, nativeMsg, convertedMsg ] allHistory.append( line ) #if messageType == OpenMaya.MCommandMessage.kError : # and 'Syntax error' in nativeMsg: # return for reporter in reporters.values():
def boCmdEncode(cmd): return cmds.encodeString(cmd).replace("\\\"","\"")