我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用maya.cmds.file()。
def saveScreenshot(self, name, directory=DIRECTORY): path = os.path.join(directory, '%s.jpg' % name) # We'll fit the view to the objects in our scene or our selection cmds.viewFit() # We'll change our render format to jpg cmds.setAttr("defaultRenderGlobals.imageFormat", 8) # This is the value for jpeg # Finally we'll save out our image using the playblast module # There are a lot of arguments here so it's good to use the documentation to know what's going on cmds.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, startTime=1, endTime=1, viewer=False) # Return the path of the file we saved return path # This will be our first Qt UI! # We'll be creating a dialog, so lets start by inheriting from Qt's QDialog
def save(self): # We start off by getting the name in the text field name = self.saveNameField.text() # If the name is not given, then we will not continue and we'll warn the user # The strip method will remove empty characters from the string, so that if the user entered spaces, it won't be valid if not name.strip(): cmds.warning("You must give a name!") return # We use our library to save with the given name self.library.save(name) # Then we repopulate our UI with the new data self.populate() # And finally, lets remove the text in the name field so that they don't accidentally overwrite the file self.saveNameField.setText('')
def delete_bookmark(ui, value): ''' ??????????? :param type: ?????????? :param value: ?????? :return: ''' if ui.radio_bookmark_file.isChecked(): type = 'file' elif ui.radio_bookmark_directory.isChecked(): type = 'directory' option_var_name = get_bookmark_option_var_name(type) ls = cmds.optionVar(q=option_var_name) if ls != 0: if value in ls: ls.remove(value) cmds.optionVar(ca=option_var_name) [cmds.optionVar(sva=(option_var_name, i)) for i in ls] return
def _maintained_selection_context(): """Maintain selection during context Example: >>> scene = cmds.file(new=True, force=True) >>> node = cmds.createNode("transform", name="Test") >>> cmds.select("persp") >>> with maintained_selection(): ... cmds.select("Test", replace=True) >>> "Test" in cmds.ls(selection=True) False """ previous_selection = cmds.ls(selection=True) try: yield finally: if previous_selection: cmds.select(previous_selection, replace=True, noExpand=True) else: cmds.select(deselect=True, noExpand=True)
def process(self, name, namespace, context, data): from maya import cmds cmds.loadPlugin("AbcImport.mll", quiet=True) nodes = cmds.file( self.fname, namespace=namespace, # Prevent identical alembic nodes # from being shared. sharedReferenceFile=False, groupReference=True, groupName=namespace + ":" + name, reference=True, returnNewNodes=True ) self[:] = nodes
def process(self, instance): from maya import cmds from avalon import maya with maya.maintained_selection(): cmds.select(instance, replace=True) nodes = cmds.file( constructionHistory=True, exportSelected=True, preview=True, force=True, ) self.assemblies[:] = cmds.ls(nodes, assemblies=True) if not self.assemblies: raise Exception("No assembly found.") if len(self.assemblies) != 1: self.assemblies = '"%s"' % '", "'.join(self.assemblies) raise Exception( "Multiple assemblies found: %s" % self.assemblies )
def source_nodes(): cmds.file(new=True, force=True) source1, _ = pm.polyCube(name="source1") source2, _ = pm.polyCube(name="source2") target, _ = pm.polyCube(name="target") ch1 = att.addAttribute(source1, "chanName", "double", 0, minValue=0, maxValue=1) ch2 = att.addAttribute(source2, "chanName", "double", 0, minValue=0, maxValue=1) pm.connectAttr(ch1, source1.ty) pm.connectAttr(ch2, source2.ty)
def source_nodes(): cmds.file(new=True, force=True) pcs = pm.polyCube(name="armUI_R0_ctl") pcs2 = pm.polyCube(name="armUI_R1_ctl") attribute.addAttribute(pcs[0], "shoulder_ik", "double", 0, minValue=0, maxValue=1) ch2 = attribute.addAttribute(pcs[0], "shoulder_rotRef", "double", 0, minValue=0, maxValue=1) ch3 = attribute.addAttribute(pcs2[0], "shoulder_rotRef", "double", 0, minValue=0, maxValue=1) pm.connectAttr(ch2, pcs[0].ty) pm.connectAttr(ch3, pcs2[0].ty)
def get_temp_filename(cls, file_name): """Get a unique filepath name in the testing directory. The file will not be created, that is up to the caller. This file will be deleted when the tests are finished. @param file_name: A partial path ex: 'directory/somefile.txt' @return The full path to the temporary file. """ temp_dir = Settings.temp_dir if not os.path.exists(temp_dir): os.makedirs(temp_dir) base_name, ext = os.path.splitext(file_name) path = '{0}/{1}{2}'.format(temp_dir, base_name, ext) count = 0 while os.path.exists(path): # If the file already exists, add an incrememted number count += 1 path = '{0}/{1}{2}{3}'.format(temp_dir, base_name, count, ext) cls.files_created.append(path) return path
def execute(self): for container in self.files: operation = container['operation'].value() file_path = container['file_path'].get_path() namespace = container['namespace'].value() flag = 'i' if operation == Component.import_operation else 'r' kwargs = { flag: True, 'type': { '.ma': 'mayaAscii', '.mb': 'mayaBinary', '.fbx': 'FBX', }[os.path.splitext(file_path.lower())[-1]] } if namespace: kwargs['namespace'] = namespace cmds.file(file_path, **kwargs)
def repath(node, file, project_path): matches = [] for root, dirnames, filenames in os.walk(project_path): for x in filenames: if x == file: matches.append([root,os.path.join(root, x)]) elif x.split(".")[0] == file.split(".")[0]: #---> this second option is used when a file is useing ##### padding, we can match by name only x_ext = x.split(".")[len(x.split("."))-1] file_ext = file.split(".")[len(file.split("."))-1] if x_ext == file_ext: matches.append([root,os.path.join(root, x)]) if len(matches)>0: return cmds.filePathEditor(node, repath=matches[0][0]) return None
def test_texture_sampler(): '''Test the texture_sampler function''' # Compile and reload plugin modules from .. import plugins plugins._import_plugins() # Get texture_sampler from ..plugins.textureSampler import texture_sampler from maya import cmds cmds.file(new=True, force=True) plugins.safe_reload('textureSampler') ramp = cmds.shadingNode('ramp', asTexture=True) spotlight = cmds.shadingNode('spotLight', asLight=True) sampler = texture_sampler(ramp, [(0.5, 0.0), (0.5, 0.5), (0.5, 1.0)]) sampler.connect('color', [spotlight])
def exitRigEditMode(self): global g_rigEditModeFileName globals.noUpdate = True cmds.headsUpDisplay(rp=(2,2)) tempDir = mel.eval("getenv TEMP;") if g_rigEditModeFileName == "": cmds.file(tempDir+"\\rigModeTemp.ma",f=True,open=True) else: cmds.file(g_rigEditModeFileName,f=True,open=True) self.refreshListWidget() self.addRigBtn.setEnabled(True) self.updateAllBtn.setEnabled(True) self.rigList.setEnabled(True) self.createRigBtn.setEnabled(True) self.openNodeBtn.setEnabled(False) self.exitRigEditBtn.setEnabled(False) self.versionComboBox.setEnabled(True) if "Latest" in str(self.versionComboBox.currentText()): self.forceRigUpdate()
def test_hasattr(self): print(u"test_hasattr") cmds.file(new=True, f=True) cube = cmds.polyCube()[0] m = mtn.M(u"pCube1") assert(m.hasAttr(u"t.tx") == True) assert(m.hasAttr(u"t") == True) assert(m.hasAttr(u"tx") == True) assert(m.hasAttr(u"aaa") == False) assert(m.hasAttr(u"wm") == True) assert(m.hasAttr(u"wm[0]") == True) assert(m.hasAttr(m.t) == True) assert(m.hasAttr(m.tx) == True) assert(m.hasAttr(m.wm) == True) assert(m.hasAttr(m.wm[0]) == True)
def test_cached_attribute(self): print(u"test_cached_attribute") cmds.file(new=True, f=True) cube = cmds.polyCube()[0] m1 = mtn.M(u"pCube1") # m1._cache = True # default:True m2 = mtn.M(u"pCube1") m2._cache = False assert(m1._cache_attribute == {}) assert(m2._cache_attribute == {}) m1.t m2.t assert(u"t" in m1._cache_attribute) assert(u"t" not in m2._cache_attribute) assert(m1._cache == True) assert(m2._cache == False) assert(m1.t._cache == True) assert(m2.t._cache == False) assert(m1.t.tx._cache == True) assert(m2.t.tx._cache == False)
def test_listconnections(self): print(u"test_listconnections") cmds.file(new=True, f=True) cube = cmds.polyCube()[0] m = mtn.M(u"pCube1") cmds.setKeyframe("pCube1.tx", "pCube1.ty", "pCube1.tz", "pCube1.rx", "pCube1.ry", "pCube1.rz", "pCube1.sx", "pCube1.sy", "pCube1.sz") assert(type(m.listConnections()) == list) assert(m.listConnections(asGenerator=True).__class__.__name__ == "generator") m.listConnections(asGenerator=True, c=True) m.listConnections(asGenerator=True, p=True) m.listConnections(asGenerator=True, c=True, p=True) m.listConnections(c=True) m.listConnections(p=True) m.listConnections(c=True, p=True) assert(m.listConnections(c=True,s=False) == []) assert(m.listConnections(p=True,s=False) == [])
def import_animation(*args): """imports the anim (from rand selection of list items) onto selected objs""" lo, hi = cmds.intFieldGrp(widgets["rangeIFG"], q=True, v=True) rand = cmds.radioButtonGrp(widgets["randRBG"], q=True, sl=True) clips = cmds.textScrollList(widgets["animTSL"], q=True, si=True) path = cmds.textFieldButtonGrp(widgets["impPathTFG"], q=True, tx=True) options = {"targetTime":3, "time": 1, "option":"insert", "connect":1} delKeys = cmds.checkBoxGrp(widgets["delCBG"], q=True, v1=True) sel = cmds.ls(sl=True) for obj in sel: startF = cmds.currentTime(q=True) if rand == 1: startF = random.randint(lo, hi) cmds.currentTime(startF) if delKeys: delete_later_keys(obj, startF) cmds.select(obj, r=True) myClip = random.choice(clips) animPath = "{0}/{1}".format(path, myClip) cmds.file(animPath, i = True, type = "animImport", ignoreVersion = True, options = "targetTime={0};time={1};copies=1;option={2};pictures=0;connect={3};".format(options["targetTime"], startF, options["option"], options["connect"]), preserveReferences=True) cmds.select(sel, r=True)
def lock(): """Lock scene Add an invisible node to your Maya scene with the name of the current file, indicating that this file is "locked" and cannot be modified any further. """ if not cmds.objExists("lock"): with lib.maintained_selection(): cmds.createNode("objectSet", name="lock") cmds.addAttr("lock", ln="basename", dataType="string") # Permanently hide from outliner cmds.setAttr("lock.verticesOnlySet", True) fname = cmds.file(query=True, sceneName=True) basename = os.path.basename(fname) cmds.setAttr("lock.basename", basename, type="string")
def maintained_selection(): """Maintain selection during context Example: >>> scene = cmds.file(new=True, force=True) >>> node = cmds.createNode("transform", name="Test") >>> cmds.select("persp") >>> with maintained_selection(): ... cmds.select("Test", replace=True) >>> "Test" in cmds.ls(selection=True) False """ previous_selection = cmds.ls(selection=True) try: yield finally: if previous_selection: cmds.select(previous_selection, replace=True, noExpand=True) else: cmds.select(deselect=True, noExpand=True)
def save(self): """ Funcrtion saves the execution times of commands to the file. """ i = 0 scores = [] while i < self.target_list.count(): scores.append(self.target_list.item(i).text()) i += 1 path = QtGui.QFileDialog.getExistingDirectory(None, 'Wybierz folder do zapisu pliku wyniki.txt', 'D:/Dane/Projekty/licencjat/') with open(path + '/wyniki_Maya.txt', 'w') as file_: for score in scores: file_.write(score + '\n')
def load(self, name): path = self[name]['path'] # We tell the file command to import, and tell it to not use any nameSpaces cmds.file(path, i=True, usingNamespaces=False) # This function will save a screenshot to the given directory with the given name
def file_context_menu(self, pos): add_menu_label = ['Add to bookmark'] action = self.build_context_menu(pos, self.view_file, self.file_model, add_menu_label) if action == add_menu_label[0]: path = self.get_view_select(self.view_file, self.file_model) add_bookmark('file', path) self.setup_view_bookmark()
def get_bookmark_option_var_name(type): if type == 'file': return 'SceneExplorer_BookmarkFileList' elif type == 'directory': return 'SceneExplorer_BookmarkDirectoryList'
def get_bookmark(ui): ''' ???????????????????? :param ui: ui??????? :return: ???????? ''' if ui.radio_bookmark_file.isChecked(): type = 'file' elif ui.radio_bookmark_directory.isChecked(): type = 'directory' option_var_name = get_bookmark_option_var_name(type) ls = cmds.optionVar(q=option_var_name) if ls == 0: ls = [] return ls
def execute(my): # get the sobject passed in sobject = my.get_input_value('sobject') code = sobject.get('code') search_key = my.get_package_value("search_key") # get the designated local directory to put temporary files tmp_dir = my.get_package_value("local_dir") path = "%s/%s.ma" % (tmp_dir, code) context = my.get_package_value("asset_context") # FIXME: ignore subcontext for now #subcontext = my.get_package_value("asset_sub_context") #if subcontext: # context = "%s/%s" % (context, subcontext) # save out the file cmds.file( rename=path) cmds.file( save=True, type='mayaAscii') # checkin the file that was just saved my.server.upload_file(path) snapshot = my.server.simple_checkin(search_key, context, path) # add a mock dependency snapshot_code = snapshot.get("code") my.server.add_dependency(snapshot_code, "C:/tt.pdf")
def open_scene(file_path, dir_path, all_process): # check if scene need saving new_scene = mel.eval('saveChanges("file -f -new")') if bool(new_scene): print('Opening: ' + file_path) # set_workspace(dir_path, all_process) cmds.file(file_path, open=True, force=True) # cmds.file(q=True, location=True) #prtint current scene path
def import_scene(file_path): print('Importing: ' + file_path) cmds.file(file_path, i=True)
def reference_scene(file_path): print('Referencing: ' + file_path) cmds.file(file_path, r=True)
def clear(): shutil.rmtree(self._tempdir) self._tempdir = tempfile.mkdtemp() cmds.file(new=True, force=True) cmds.file(rename="temp.ma")
def process(self, name, namespace, context, data): from maya import cmds nodes = cmds.file( self.fname, namespace=namespace, reference=True, returnNewNodes=True, groupReference=True, groupName=namespace + ":" + name ) self[:] = nodes
def process(self, context): from maya import cmds from avalon import maya assert all(result["success"] for result in context.data["results"]), ( "Integration failed, aborting.") maya.lock() with maya.lock_ignored(): cmds.file(save=True, force=True)
def process(self, context): """Inject the current working file""" current_file = cmds.file(query=True, sceneName=True) context.data['currentFile'] = os.path.normpath(current_file)
def load_data(file_path): """Load a skeleton hierarchy from the given json data file. No nodes will be created in Maya. :param file_path: Json file on disk. :return: The hierarchy data loaded from disk. """ fh = open(file_path, 'r') data = json.load(fh) fh.close() return data
def load(file_path=None): """Load a skeleton hierarchy from the given json data file and generates the hierarchy in Maya. :param file_path: Json file on disk. :return: The hierarchy data loaded from disk. """ if file_path is None: file_path = cmds.fileDialog2(fileFilter='Skeleton Files (*.json)', dialogStyle=2, caption='Export Skeleton', fileMode=1, returnFilter=False) if file_path: file_path = file_path[0] else: return data = load_data(file_path) create_node(data) return data
def set_file_new(value): """Set whether a new file should be created after each test. @param value: True or False """ Settings.file_new = value
def tearDown(self): if Settings.file_new and CMT_TESTING_VAR not in os.environ.keys(): # If running tests without the custom runner, like with PyCharm, the file new of the TestResult class isn't # used so call file new here cmds.file(f=True, new=True)
def test_get_and_rebuild_data(self): data = skeleton.get_data(self.group) cmds.file(new=True, f=True) skeleton.create_node(data) self.assert_hierarachies_match()
def test_export_and_import_data(self): json_file = self.get_temp_filename('skeleton.json') skeleton.dump(self.group, json_file) cmds.file(new=True, f=True) skeleton.load(json_file) self.assert_hierarachies_match()
def new_scene(): checkState() return cmds.file(new=True, f=True)
def save_scene_as(path = None, file_name = None): if os.path.exists(path): if file_name: fullpath = os.path.join(path,file_name) cmds.file(rename = fullpath) return cmds.file(s=True, type="mayaAscii")
def open_scene(path = None): if os.path.exists(path): checkState() insert_recent_file(path) opend = cmds.file(path, o = True, f = True, esn = True) logging.info("{}".format(opend)) return opend
def current_open_file(): return cmds.file(q=True,sn=True)
def checkState(): # check if there are unsaved changes fileCheckState = cmds.file(q=True, modified=True) # if there are, save them first ... then we can proceed if fileCheckState: # This is maya's native call to save, with dialogs, etc. # No need to write your own. if dlg.warning("warning", "Scene Not Saved", "Scene Not Saved, Do you want to save it first?"): cmds.SaveScene() pass else: pass
def import_scene(path = None): if os.path.exists(path): namesspace = files.file_name_no_extension(files.file_name(path)) return cmds.file(path, i = True, f = True, ns = namesspace, esn = False)
def new_scene_from_selection(project_path = None, mode = "include"): temp_file = os.path.join(project_path, "scenes", "temp_%s.ma"%(id_generator())) logging.info(temp_file) sel = cmds.ls(sl=True) if len(sel)>0: if mode == "include": saved_file = cmds.file(temp_file, type='mayaAscii', exportSelected=True, expressions=True, constraints=True, channels=True, constructionHistory=True, shader=True) if mode == "exclude": saved_file = cmds.file(temp_file, type='mayaAscii', exportSelected=True, expressions=False, constraints=False, channels=False, constructionHistory=False, shader=True) if saved_file: open_scene(saved_file) return saved_file return None
def open_file(file_path, file_type): u"""???????????? :param file_path: ?????? :type file_path: unicode :param file_type: ??????? :type file_type: unicode """ cmds.file(force=True, new=True) mel.eval('openRecentFile("{0}", "{1}");'.format(file_path, file_type))
def get_current_scenename(): path = cmds.file(query=True, sceneName=True) if path: return os.path.splitext(os.path.basename(path))[0] return None
def open_file(filepath): """Open file using OS default settings""" if sys.platform.startswith('darwin'): subprocess.call(('open', filepath)) elif os.name == 'nt': os.startfile(filepath) elif os.name == 'posix': subprocess.call(('xdg-open', filepath)) else: raise NotImplementedError("OS not supported: {0}".format(os.name))
def _fix_playblast_output_path(filepath): """Workaround a bug in maya.cmds.playblast to return correct filepath. When the `viewer` argument is set to False and maya.cmds.playblast does not automatically open the playblasted file the returned filepath does not have the file's extension added correctly. To workaround this we just glob.glob() for any file extensions and assume the latest modified file is the correct file and return it. """ # Catch cancelled playblast if filepath is None: log.warning("Playblast did not result in output path. " "Playblast is probably interrupted.") return # Fix: playblast not returning correct filename (with extension) # Lets assume the most recently modified file is the correct one. if not os.path.exists(filepath): directory = os.path.dirname(filepath) filename = os.path.basename(filepath) # check if the filepath is has frame based filename # example : capture.####.png parts = filename.split(".") if len(parts) == 3: query = os.path.join(directory, "{}.*.{}".format(parts[0], parts[-1])) files = glob.glob(query) else: files = glob.glob("{}.*".format(filepath)) if not files: raise RuntimeError("Couldn't find playblast from: " "{0}".format(filepath)) filepath = max(files, key=os.path.getmtime) return filepath
def capture_scene(options): """Capture using scene settings. Uses the view settings from "panel". This ensures playblast is done as quicktime H.264 100% quality. It forces showOrnaments to be off and does not render off screen. :param options: a collection of output options :type options: dict :returns: Full path to playblast file. :rtype: str """ filename = options.get("filename", "%TEMP%") log.info("Capturing to: {0}".format(filename)) options = options.copy() # Force viewer to False in call to capture because we have our own # viewer opening call to allow a signal to trigger between playblast # and viewer options['viewer'] = False # Remove panel key since it's internal value to capture_gui options.pop("panel", None) path = capture.capture(**options) path = _fix_playblast_output_path(path) return path