首页 > 解决方案 > 使用 try,但使用 Maya Python 检查以确保选择中的项目是正确的节点类型

问题描述

**在检查选定节点的节点类型时如何知道何时使用 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  

标签: pythonmaya

解决方案


简而言之,您将用于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')

推荐阅读