Python maya.cmds 模块,workspace() 实例源码

我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用maya.cmds.workspace()

项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def browse(self, line_edit, relative_to_combobox):
        root = cmds.workspace(q=True, rd=True)
        file_path = cmds.fileDialog2(fileFilter=self.filter, dialogStyle=2, caption=self.name,
                                     fileMode=1, returnFilter=False, startingDirectory=root)
        if file_path:
            # Modify the file path to be a path based on the relative_to value
            file_path = file_path[0].replace('\\', '/')
            relative_to = relative_to_combobox.currentText().replace('\\', '/')
            if relative_to == FilePathField.project_root:
                project_root = cmds.workspace(q=True, rd=True).replace('\\', '/')
                file_path = file_path.replace(project_root, '')
            elif relative_to == FilePathField.full_path:
                # Do nothing, just take the full path
                pass
            else:
                # Account for if the relative_to is an environment variable.
                file_path = os.path.expandvars(file_path)
                # Account for if the relative_to is an actual file path.
                file_path = re.sub('^{0}'.format(relative_to), '', file_path)
            line_edit.setText(file_path)
项目:Modular_Rigging_Thesis    作者:LoganKelly    | 项目源码 | 文件源码
def updateFileName(self,fileName):
        modelFile = open(fileName)
        modelFileTextLines = modelFile.readlines()
        modelFile.close()
        self.geoNameList.clear()
        for line in modelFileTextLines:
            if 'createNode transform -n' in line:
                modelName = line.split('"')[1]
                item = QListWidgetItem(self.geoNameList)
                item.setText(modelName)
        projectDir = cmds.workspace(q=True,rd=True)
        found = fileName.compare(projectDir)
        if found is not 0:
            fileName = "./"+fileName[len(projectDir):]
        self.fileLocation.setText(fileName)
        #self.widgetsUpdated.emit()
项目:core    作者:getavalon    | 项目源码 | 文件源码
def _set_project():
    """Sets the maya project to the current Session's work directory.

    Returns:
        None

    """
    workdir = api.Session["AVALON_WORKDIR"]

    try:
        os.makedirs(workdir)
    except OSError as e:
        # An already existing working directory is fine.
        if e.errno == errno.EEXIST:
            pass
        else:
            raise

    cmds.workspace(workdir, openWorkspace=True)
项目:SceneExplorer    作者:mochio326    | 项目源码 | 文件源码
def get_current_ptoject():
    return cmds.workspace(fn=True)
项目:SceneExplorer    作者:mochio326    | 项目源码 | 文件源码
def get_project_dir(path):
    '''
    maya??????????????
    :param path: ?????????????
    :return: ?????????None
    '''
    drive = os.path.splitdrive(path)[0]
    parent = os.path.dirname(path)
    if drive+'/' == parent:
        return None
    f = r'{0}/workspace.mel'.format(parent)
    if os.path.isfile(f):
        return parent
    return get_project_dir(parent)
项目:config    作者:mindbender-studio    | 项目源码 | 文件源码
def process(self, context):
        workspace = cmds.workspace(rootDirectory=True, query=True)
        if not workspace:
            # Project has not been set. Files will
            # instead end up next to the working file.
            workspace = cmds.workspace(dir=True, query=True)

        # Maya returns forward-slashes by default
        normalised = os.path.normpath(workspace)

        context.set_data('workspaceDir', value=normalised)

        # For backwards compatibility
        context.set_data('workspace_dir', value=normalised)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def save_queue(self):
        """Display a dialog to save a queue to disk."""
        file_path = QtWidgets.QFileDialog.getSaveFileName(self,
                                                      'Save Component Queue',
                                                      cmds.workspace(q=True, rd=True) or '',
                                                      'json files (*.json)',
                                                      '',
                                                      QtWidgets.QFileDialog.DontUseNativeDialog)[0]
        if file_path:
            self.queue_widget.queue.export(file_path)
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def get_path(self):
        """Get the resolved absolute file path."""
        relative_to = self.relative_to
        file_path = self._value
        if relative_to == FilePathField.project_root:
            root = cmds.workspace(q=True, rd=True)
            path = os.path.join(root, file_path)
        elif relative_to == FilePathField.full_path:
            path = file_path
        elif relative_to and '$' not in relative_to:
            path = os.path.join(relative_to, file_path)
        path = os.path.expandvars(path)
        return path.replace('\\', '/')
项目:maya-capture-gui    作者:Colorbleed    | 项目源码 | 文件源码
def get_project_rule(rule):
    """Get the full path of the rule of the project"""

    workspace = cmds.workspace(query=True, rootDirectory=True)
    folder = cmds.workspace(fileRuleEntry=rule)
    if not folder:
        log.warning("File Rule Entry '{}' has no value, please check if the "
                    "rule name is typed correctly".format(rule))

    return os.path.join(workspace, folder)
项目:Modular_Rigging_Thesis    作者:LoganKelly    | 项目源码 | 文件源码
def addRig(self):
        """
        Add a new item to the end of the listWidget
        """
        projectDir = cmds.workspace(q=True,rd=True)
        fileDialog = QFileDialog(self.getMayaWindow())
        fileDialog.fileSelected.connect(self.updateRigList)
        fileDialog.show()
项目:Modular_Rigging_Thesis    作者:LoganKelly    | 项目源码 | 文件源码
def populateVersionBox(self,xmlName):
        global rootNode
        currentItemText = ""
        if self.versionComboBox.count() > 0:
            currentItemText = self.versionComboBox.currentText()
        self.versionComboBox.clear()
        projPath = cmds.workspace(q=True,rd=True)
        rootNode = "MRN_"+xmlName
        xmlFilePath = cmds.getAttr(str(rootNode+".xmlPath"))
        #get the base rig name, i.e. $PROJDIR/rigDefinitions/test/test_1_1.xml would be test
        xmlFileName = xmlFilePath.split("/")[-1].split(".")[-2].split("_")[0]
        xmlDirPath = projPath + "rigDefinitions/" + xmlFileName + "/"
        rigVersions = []
        if os.path.isdir(xmlDirPath):
            #glob returns a list of files matching the regular expression
            for file in glob.glob(xmlDirPath+"*.xml"):
                tree = xml.ElementTree()
                tree.parse(file)
                rig = tree.getroot()
                version = float(rig.get('version'))
                rigVersions.append(version)
        latestXmlFile = projPath + "rigDefinitions/" + xmlFileName + ".xml"
        if os.path.isfile(latestXmlFile):
            tree = xml.ElementTree()
            tree.parse(latestXmlFile)
            rig = tree.getroot()
            version = float(rig.get('version'))
            rigVersions.append(version)
        self.versionComboBox.addItem("Latest("+str(rigVersions[-1])+")")
        rigVersions.pop()
        for version in reversed(rigVersions):
            self.versionComboBox.addItem(str(version))
        #set the version combo box to the previously selected value
        for i in range(self.versionComboBox.count()):
            itemText = self.versionComboBox.itemText(i)
            if currentItemText == itemText:
                self.versionComboBox.setCurrentIndex(i)
项目:pyblish-starter    作者:pyblish    | 项目源码 | 文件源码
def _register_root():
    """Register project root or directory of current working file"""
    root = (
        cmds.workspace(rootDirectory=True, query=True) or
        cmds.workspace(directory=True, query=True)
    )

    api.register_root(root)
项目:core    作者:getavalon    | 项目源码 | 文件源码
def _on_task_changed(*args):
    workdir = api.Session["AVALON_WORKDIR"]
    if os.path.exists(workdir):
        logger.info("Updating Maya workspace for task change to %s", workdir)
        _set_project()
    else:
        logger.warning("Can't set project for new context because "
                       "path does not exist: %s", workdir)
项目:SceneExplorer    作者:mochio326    | 项目源码 | 文件源码
def scene_open(path, set_project):
    '''
    ??????
    :return:
    '''

    def new_open():
        if set_project is True:
            cmds.workspace(project_path, openWorkspace=True)
        io.open(path, file_type, 1)
        add_rectnt_project(project_path)
        add_rectnt_file(path, file_type)

    types = {'.ma': 'mayaAscii', '.mb': 'mayaBinary', '.fbx': 'FBX', '.obj': 'OBJ'}
    if path == '':
        return None
    head, tail = os.path.split(path)
    name, ex = os.path.splitext(path)
    if ex not in types.keys():
        return None
    file_type = types[ex]
    project_path = get_project_dir(path)
    io = om.MFileIO()
    if cmds.file(q=1,sceneName=True) == '':
        new_open()
    else:
        result = cmds.confirmDialog(t='File Open', m='New Scene Open or Import Scene?',
                                    b=['New Scene', 'Import Scene', 'Cancel'],
                                    db='New Scene', cb='Cancel', ds='Cancel')
        if result == 'Cancel':
            return None
        elif result == 'New Scene':
            new_open()
        elif result == 'Import Scene':
            fbx_plugin = 'fbxmaya'
            cmds.loadPlugin('{0:}.mll'.format(fbx_plugin), qt=1)
            if fbx_plugin not in cmds.pluginInfo(q=1, ls=1):
                om.MGlobal.displayError('{0} Plugin in not loaded'.format(fbx_plugin))
                return None
            io.importFile(path, file_type, 1, str(tail.replace('.', '_')))

    # ??????????
    #ls = cmds.ls(typ='file', type='mentalrayTexture')
    #[cmds.setAttr(x + '.ftn', cmds.getAttr(x + '.ftn'), type='string') for x in ls]
    return 0
项目:Modular_Rigging_Thesis    作者:LoganKelly    | 项目源码 | 文件源码
def SaveXMLFile(self):
        #fileDialog = QFileDialog(self.getMayaWindow())
        #fileDialog.setAcceptMode(QFileDialog.AcceptSave)
        #fileDialog.fileSelected.connect(self.WriteXMLToFile)
        #fileDialog.show()

    #def WriteXMLToFile(self,fileName):
        rigNodeFound = False
        try:
            rigGuiNode = self.scene.sceneNodes["Rig"]
            rigNodeFound = True
        except KeyError:
            rigNodeFound = False
            try:
                mel.eval('error \"Rig Node Editor: No rig network exists to write to file.\";')
            except:
                return

        if rigNodeFound:
            rootElem = self.recursiveGetXML(rigGuiNode,True)
            rigName = rootElem.get('name')
            #define the most current rig definition file name and the rig definition folder
            #for older versions
            fileName = cmds.workspace(q=True,rd=True) + "rigDefinitions/" + rigName + ".xml"
            fileDirectory = cmds.workspace(q=True,rd=True) + "rigDefinitions/" + rigName + "/"
            currentFileExists = os.path.isfile(fileName)
            archiveFolderExists = os.path.isdir(fileDirectory)
            archiveFilesExist = False
            if archiveFolderExists:
                archiveFilesExist = len(os.listdir(fileDirectory)) > 0
            versionExists = False
            versionFile = None
            #check archive file names to see if version already exists
            if archiveFilesExist:
                saveVersion = rootElem.get('version')
                versionSearchString = re.sub('\.','_',saveVersion)
                for file in os.listdir(fileDirectory):
                    if versionSearchString in file:
                        versionExists = True
                        versionFile = file
            #check most recently saved file to see if version exists
            if currentFileExists:
                tree = xml.ElementTree()
                tree.parse(fileName)
                rigElem = tree.getroot()
                lastVersion = rigElem.get('version')
                saveVersion = rootElem.get('version')
                if lastVersion == saveVersion:
                    versionExists = True
                    versionFile = fileName
            self.FileSave(currentFileExists, archiveFolderExists, versionExists, versionFile, fileName, fileDirectory,rootElem)

    #depending on the boolean flags provided, save the xml file in different ways
项目:Modular_Rigging_Thesis    作者:LoganKelly    | 项目源码 | 文件源码
def enterRigEditMode(self,*args):
        self.versionComboBox.setEnabled(False)
        newRig = args[0]
        global g_rigEditModeFileName
        global xmlPath
        global rootNode
        projectDir = cmds.workspace(q=True,rd=True)
        #remove the HUD item at (2,0) if one is present
        cmds.headsUpDisplay(rp=(2,2))
        #add our HUD item for the rig edit mode
        cmds.headsUpDisplay("",s=2,b=2,ba="center",lfs="large",dw=50,l="Rig Edit Mode")

        tempDir = mel.eval("getenv TEMP;")
        #get the path to the XML file and save it for later use
        if newRig is False:
            current = self.rigList.currentItem()
            rootNode = "MRN_"+current.text()
            xmlPath = cmds.getAttr(str(rootNode+".xmlPath"))
            #write over temporary rig file
            shutil.copy(xmlPath, tempDir+"/rigTemp.xml")
            xmlPath = tempDir+"/rigTemp.xml"
        else:
            rootNode = ""
            xmlPath = ""


        #save the scene to a file, and load a new, empty scene


        g_rigEditModeFileName = cmds.file(q=True,sceneName=True)
        if g_rigEditModeFileName == "":
            cmds.file(rn=tempDir+"\\rigModeTemp.ma")
        cmds.file(f=True,save=True,type="mayaAscii")
        cmds.file(f=True,new=True)

        #load the rig file into the current scene
        if newRig is False:
            commandString = "loadRig -p \""+xmlPath+"\";"
            rigName = mel.eval(commandString)


        self.refreshListWidget()
        self.addRigBtn.setEnabled(False)
        self.updateAllBtn.setEnabled(False)
        self.enterRigEditBtn.setEnabled(False)
        self.rigList.setEnabled(False)
        self.createRigBtn.setEnabled(False)
        self.openNodeBtn.setEnabled(True)
        self.exitRigEditBtn.setEnabled(True)