一半君的总结纸

听话只听一半君

#124 如何上下移动channel box里的user attribute的位置

rigging里经常会需要把属性上下移动位置,此时你可以…

from contextlib import contextmanager
import maya.cmds as MC

@contextmanager
def undo():
    try:
        yield
    finally:
        MC.undo()


@contextmanager
def restoreSelection():
    sel = MC.ls(sl=1)
    try:
        yield
    finally:
        MC.select(sel)


@contextmanager
def pauseRefresh():
    if not MC.about(batch=1):
        MC.refresh(suspend=True)
        try:
            yield
        finally:
            MC.refresh(suspend=False)
    else:
        yield

def reorderAttr(obj, attr, direction=1):

    allAttrs = MC.listAttr(obj, k=1, ud=1)
    index = allAttrs.index(attr)
    operations = len(allAttrs) - (index + direction) % len(allAttrs)
    for n in range(operations):
        with restoreSelection(), pauseRefresh(), undo():
            MC.deleteAttr(obj, at=allAttrs[index])
            if n == 0:
                index += direction
                index %= len(allAttrs)

        allAttrs = MC.listAttr(obj, k=1, ud=1)

如果想要高端一点可以这样, decorator可以在pypi安装,但是他不是必须的,这样可以把context manager当decorator用

from decorator import decorator

def contextDecorator(contextObj, *contextArgs, **contextKwargs):
    @decorator
    def decorated(func, *args, **kwargs):
        with contextObj(*contextArgs, **contextKwargs):
            return func(*args, **kwargs)

    return decorated

# 然后就可以
@contextDecorator(restoreSelection)
def someFunction():
    pass
reorder in action

参考:
ffcast GIF-Howto
Function acting as both decorator and context manager in Python?
decorator module vs functools.wraps

One response to “#124 如何上下移动channel box里的user attribute的位置

  1. kekejiu 六月 25, 2019 @ 8:34 下午

    awesome !!!

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s

%d 博主赞过: