python - 使用 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
解决方案
简而言之,您将用于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')
推荐阅读
- python - 如何在 Python 中为水平条形图绘制百分比标签?
- c++ - 如何使用 mongocxx/bsoncxx 驱动程序 (C++) 将 JPEG / PDF 文件上传到 mongodb
- angular - 不是函数角离子
- python - 如何从 Django 的愿望清单中删除产品?
- javascript - 如何记录用户关闭烧瓶视图的时间?
- css - 如何在 React 中为伪类动态添加 CSS 样式
- android-studio - 网站抓取html类识别问题
- r - 用于 3D PCA 的 R 包(分数图和载荷图(箭头))?
- mysql - docker mysql 卷组成连接错误
- c# - 如何在 C# 中以编程方式保存用户使用 CTRL-C 复制到剪贴板的 Outlook 电子邮件附件(例如 PDF)