Python 嵌套命名空间删除

Python 嵌套命名空间删除,python,namespaces,maya,Python,Namespaces,Maya,我编写脚本是为了在不使用/打开名称空间编辑器的情况下删除名称空间(嵌套或非嵌套),前提是在名称空间中没有内容的情况下满足条件 这样做时,我遇到了这个问题,无法使用cmds.namespace(rm=”“) 我已经找到了一个较长的解决方法,但是我被卡住了,因为输出是列表中的unicode,我似乎无法将其转换为字符串 nsLs = cmds.namespaceInfo( lon=True) # nsLs Result: [u'UI', u'camera01', u'shared', u'v02',

我编写脚本是为了在不使用/打开名称空间编辑器的情况下删除名称空间(嵌套或非嵌套),前提是在名称空间中没有内容的情况下满足条件

这样做时,我遇到了这个问题,无法使用
cmds.namespace(rm=”“)

我已经找到了一个较长的解决方法,但是我被卡住了,因为输出是列表中的unicode,我似乎无法将其转换为字符串

nsLs = cmds.namespaceInfo( lon=True)
# nsLs Result: [u'UI', u'camera01',  u'shared', u'v02', u'v03']

defaultNs = ["UI", "shared", "camera01"]

diffLs = [item for item in nsLs if item not in defaultNs]
# diffLs Result: [u'v02', u'v03']

for ns in diffLs:
    nsNest = cmds.namespaceInfo(ns, lon=True)
    # nsNest Result:    [u'v02:new_run01']
    #                   [u'v03:new_run01']
    cmds.namespace(rm=str(nsNest))
因此,我使用的“删除”标志不起作用,因为遇到以下错误:

# Error: No namespace matches name: '[u'v02:new_run01']'.
# Traceback (most recent call last):
#   File "<maya console>", line 13, in <module>
# RuntimeError: No namespace matches name: '[u'v02:new_run01']'. #
#错误:没有与名称匹配的命名空间:“[u'v02:new_run01']”。
#回溯(最近一次呼叫最后一次):
#文件“”,第13行,在
#RuntimeError:没有命名空间与名称“[u'v02:NewURun01']”匹配#
我输入的上述代码仅用于嵌套的名称空间,尽管它仍然无法“实现”结果,也不是很灵活(假设场景中只有一个嵌套级别),但有什么方法可以纠正这一点吗

此外,如果任何人有任何解决方案/方法可以在不使用名称空间编辑器的情况下删除名称空间,当然,如果名称空间编辑器


如果
名称空间
命令需要一个字符串(在本例中为
'v02:new\u run01'
),则将字符串化列表本身传递给它(在本例中为
'[u'v02:new\u run01']
)。由于您有
lon=True
标志,因此该命令将始终返回一个列表。您应该确保从中提取元素并将其发送到
namespace
命令

您只需从列表而不是整个列表中传递元素:

for ns in diffLs:
    nsNest = cmds.namespaceInfo(ns, lon=True)
    # nsNest Result:    [u'v02:new_run01']
    #                   [u'v03:new_run01']
    if nsNest:
        cmds.namespace(rm=nsNest[0])

希望对您有所帮助。

这是下面的代码,其中它删除了嵌套名称空间的任何级别,假设它包含空内容

import maya.cmds as mc

defaults = ['UI', 'shared']

def num_children(ns):
    return ns.count(':')

namespaces = [ns for ns in mc.namespaceInfo(lon=True, r=True) if ns not in defaults]
sorted_ns = sorted(namespaces, key=num_children, reversed=True)
for ns in sorted_ns:
    try:
        mc.namespace(rm=ns)
    except RuntimeError as e:
        pass
感谢一位在这方面提供帮助的朋友:)

要删除所有可能需要使用recursemergeNamespaceWithParent标志的内容。这样,它将删除所有名称空间,并将其作为root的父级

# Gathering and deleting all namespaces
name_space = [item for item in pm.namespaceInfo(lon=True, recurse=True) if item not in ["UI", "shared"]]
# Sort them from child to parent, That's order we need to delete
sorted_ns_namespace = sorted(name_space, key=lambda ns: ns.count(':'), reverse=True)

for ns in sorted_ns_namespace:
    pm.namespace(removeNamespace=ns, mergeNamespaceWithParent=True)

它正在工作。想知道您是否知道确定名称空间嵌套级别的任何方法?请在此处发布。如果你觉得答案很有帮助,就考虑投票吧。