How do I get a list of commands from maya undo queue?

Because undoInfo -q -pq didn’t return anything, and it has a # in each line it prints out, just like other maya commands. So I guess the print out goes to stderr ?

Why this code doesn’t work? It should capture the print out in f ? reference

from contextlib import contextmanager

@contextmanager
def stderr_redirector(stream):
    old_stderr = sys.stderr
    sys.stderr = stream
    
    old_stdout = sys.stdout
    sys.stdout = stream
    try:
        yield
    finally:
        sys.stderr = old_stderr
        sys.stdout = old_stdout
        
import io
f=io.StringIO()

with stderr_redirector(f):
    mc.undoInfo(q=1,pq=1)

print '-'*30
print f.getvalue()

from contextlib import contextmanager
import re

def catchOutput(msg, *args):
    f.write("Caught: %s
" % msg)

@contextmanager
def output_redirector():
    catchOutput_id = om.MCommandMessage.addCommandOutputCallback(catchOutput)
    try:
        yield
    finally:
        om.MCommandMessage.removeCallback(catchOutput_id)

import io
f=io.StringIO()

def get_undo_queue():
   
    with output_redirector():
        mc.undoInfo(q=1,pq=1)
    
    undo_cmds=[]    
    for line in f.getvalue().split('
'):
        if len(line.strip(' ')):
            id,code = re.search('(?<=Caught:\s)(\d*)\:\s(.*)',line).groups()
            print id,'-->',code
            undo_cmds.append( (id,code))
        
    return undo_cmds
    
    
cmd_list=get_undo_queue()

reference

1 Like