使用 try,除了 Maya Python 检查以确保选择中的项目是正确的节点类型

using try, except with Maya Python to check to make sure items in a selection are the correct node type

**我正在努力了解在检查所选节点的节点类型时如何知道何时使用 try/except 和 if/else,以及如何在类似的情况下使用 try/except下面。

我想做这样的事情:**

selected_nodes = cmds.ls(sl = True)

for selected_node in selected_nodes:

    #example one

    validate_node_type = validate_nodes(selected_node)
        if validate_node_type == True
            return True
        else:
            return False

    def validate_nods(selected_node):
        node_type = cmds.node_type(selected_node)
        if node_type == 'file':
            return True
        else:
            return False
    
    #example two, or is better to use try/except?

    try:
        validate_nodes(selected_node)
        return True
    except:
        return False
    
    def validate_nodes(selected_node):
        selected_node_type = nodeType(selected_node)
        try:
            selected_node_type == 'file'
            return True
        except:
            return False  

简而言之,您将使用 if/else 执行逻辑检查,并使用 try/except 包装可能引发 错误的代码 并防止其余的执行您的代码。

在您的具体示例中,node_type = cmds.nodeType(selected_node) 可能会 抛出错误,因此如果您要在任何地方使用 try/except,可能就是这个地方.

但有时,抛出错误是完全正确的做法——尤其是在操作无人值守的情况下。

就个人而言,我会将您的代码重构为如下所示:

def validate_fileNodes(nodes):
    '''Check if a single or list of objects are of type `file`
    
    Args:
        nodes (str|list [str]): Nodes to check

    Returns:
        bool: True if all matches, False otherwise
    '''

    if not isinstance(nodes, (list, tuple)):
        nodes = [nodes]
    
    for node in nodes:
        if cmds.nodeType(node) != 'file':
            return False

    return True

selected_nodes = cmds.ls(sl=True)
valid_files = validate_fileNodes(selected_nodes)

print('Selected nodes are valid files? {}'.format(valid_files))

请记住,如果您向它提供错误信息,可能 会抛出一个错误,但是您如何处理它可能应该在您的验证函数之外处理。

编辑: 在回答评论时,为了发现错误我会在这里做:

selected_nodes = cmds.ls(sl=True)
valid_files = None

try:
    # This method may raise an error, but we catch it here instead of in the method itself
    valid_files = validate_fileNodes(selected_nodes)
except Exception as e:
    print('validate_fileNodes method raised an exception: {}'.format(e))

if valid_files == True:
    print('Selected nodes are valid!')
elif valid_files == False:
    print('Selected nodes are not valid, but the check went well')
else:
    print('The check failed. We dont know whats going on here')

你可能把这个复杂化了。如果您只想检查节点列表是否为文件类型,那么它几乎可以在一行中完成:

import maya.cmds as cmds

def is_node_type(objs, node_type="file"):
    return len(cmds.ls(objs, type=node_type)) > 0

is_node_type(cmds.ls(sl=True))  # Check with current selection.

您可以将对象列表传递给 cmds.ls 并将参数 type 指定给您要检查的任何内容。如果对象集合中存在该类型,则直接返回该类型的长度将 return True,如果不存在,则返回 False。由于该函数还有 node_type 参数,您可以轻松地将其更改为其他参数,而无需对其进行硬编码。

到那时你可以用它做任何你想做的事。通常你可以坚持 if else 条件。虽然在某些情况下嵌套许多 if 语句可能会冗长,但在这种情况下,您可以预测可能出现的错误并使用 try except 捕获它。我相信这就像 EAFP (Easier to ask for forgiveness than permission)。在某些情况下,您别无选择,只能使用 try,这通常是在涉及外部因素时,例如依赖您的互联网连接或连接到某些可能已关闭的服务器。