Skip to content

Instantly share code, notes, and snippets.

@yamahigashi
Created September 15, 2020 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamahigashi/2bd824791d3fcf9f5dfeac5b3f35ec6a to your computer and use it in GitHub Desktop.
Save yamahigashi/2bd824791d3fcf9f5dfeac5b3f35ec6a to your computer and use it in GitHub Desktop.
Context manager for redirecting Autodesk Maya's logging to given file path, to use as `with` statement.
from contextlib import contextmanager
from pathlib import Path
@contextmanager
def redirect_log(logfile_path):
# type: (Text) -> Generator[None, None, None]
"""Function: Context manager for redirecting maya's log to given path, to use as `with` statement.
Scenario: giving None to logfile_path
then: do nothing
Scenario: given existing path
then: redirect to path before, do main job then re-redirect to original
Scenario: given non-existing path
then: touch file, redirect to path before, do main job then re-redirect to original
"""
import maya.cmds as cmds
if not logfile_path:
yield
return
logfile = Path(logfile_path)
logfile.touch()
is_original_redirected = cmds.scriptEditorInfo(q=True, writeHistory=True)
original_log = cmds.scriptEditorInfo(q=True, historyFilename=True)
try:
cmds.scriptEditorInfo(historyFilename=logfile.as_posix(), writeHistory=True)
yield
finally:
cmds.scriptEditorInfo(writeHistory=False)
if is_original_redirected:
cmds.scriptEditorInfo(writeHistory=True)
if original_log:
cmds.scriptEditorInfo(historyFilename=original_log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment