Skip to main content
 首页 » 编程设计

python之如何中止通过 python 中的 cmds.file 启动的 Maya 中的文件加载

2025年01月19日7Renyi-Fan

我有在 Maya 中对文件运行批处理操作的代码。实际的实现并不重要,只要知道它会得到一个文件路径列表,maya 打开文件,然后依次对每个文件执行操作。

如果引用出于某种原因(例如无效路径)无效,我想中止整个场景的加载并跳到批处理列表中的下一个场景。

查看本网站和其他地方的其他问题时,我只能看到用户询问如何查询引用文献。我已经有了一个合理的函数来执行此操作,在该函数返回无效的引用路径后我该怎么办,这让我很困惑。

解决无效引用路径历来是通过弹出窗口手动完成的,但是在大批量不断维护 Maya 实例是不可行的。也不会抑制弹出窗口本身,因为我相信它仍会打开文件,并在处于无效状态时在现场运行批处理操作。

我已经通过了the maya cmds python module尝试不加载引用,但是当使用 loadReferenceDepth 标志和 cmds.file 时,我仍然会收到一个弹出窗口:

cmds.file(r'c:\path\to\file.ma', o=1, f=1, lrd='none')  #invalid ref popup during file cmd 

第二种方法是查看 maya open api并在 before open 事件上注册回调。下面的代码在功能上与批处理的设置方式相同:

import maya.OpenMaya as OpenM 
 
batchFileList = [r"c:\path\to\file.ma", r"c:\path\to\file2.ma"] 
 
def _test_raise_exception(arg0, arg1, arg2): 
    #pretending that a file ref failed below. Ref path validation code would go here. 
    print '\n'*5+'Test Logging'+'\n'*5 
    return False 
 
cId = OpenM.MSceneMessage.addCheckFileCallback(OpenM.MSceneMessage.kBeforeOpenCheck, _test_raise_exception) 
 
for file_ in batchFileList: 
    try: 
        rv = cmds.file(file_, o=1) 
        #do stuff to the maya scene here 
    except: 
        #something didn't validate on load, except and skip, logging the occurrence. 
        print 'load cancelled' 
 
OpenM.MSceneMessage.removeCallback(cId) 

但是,即使 addCheckFileCallback indicates that if the callback function returns False the operation is aborted , 无论如何都会加载文件。

同样,将 return False 替换为 raise RuntimeError 不会让我捕获异常。相反,cmds.file 完成并仅在日志中打印出一条小消息,提示“python 回调失败”。 The python open api docs say that the bindings prefer exceptions over MStatus return codes though, so I would've expected that to work.

We have removed the MStatus class. Python exceptions must be used instead of MStatus.

我是不是漏掉了什么?必须有办法做到这一点。构建一个非常粗糙的 .ma 解析器是另一种选择,但这意味着放弃对 .mb 文件的支持,这是我不想做的。

感谢您的宝贵时间!

请您参考如下方法:

您是否尝试过使用 lrd = 'none' 和 prompt=0 独立运行 cmds.file?这应该可以让您在没有对话框的情况下进入文件,这样您就可以在加载引用之前预先检查它们,如果它们很无聊则跳过文件。