Utilities

Environment

addToEnv(env, newPaths)

Adds the specified environment paths to the environment variable if the path doesn’t already exist.

Parameters:
  • env (str) – The environment variable name

  • newPaths (iterable(str)) – A iterable containing strings

removeFromEnv(env, values)

Removes the specified values from the environment variable.

The comparison is an exact match between os.pathsep.

Parameters:
  • env (str) – The environment variable name to update.

  • values (list[str]) – The values to remove from the env.

Returns:

The new environment variable value.

Return type:

str

isInMaya(executable=None)

Determines if the current running executable is maya.exe

Returns:

True if running maya.exe

Return type:

bool

isMayapy(executable=None)

Determines if the current running executable is mayapy.exe

Returns:

True if running mayapy.exe

Return type:

bool

isMayaBatch(executable=None)

Determines if the current running executable is mayabatch.exe

Returns:

True if running mayapy.exe

Return type:

bool

isMaya(executable=None)

Combination of isMayapy, isInMaya and isMayaBatch

Parameters:

executable (str | None) – True if running maya and it’s variants

Returns:

Return type:

bool

isIn3dsmax(executable=None)

Determines if the current running executable is 3dsmax.exe

Returns:

True if running 3dsmax.exe

Return type:

bool

isInMotionBuilder(executable=None)

Determines if the current running executable is motionbuilder.exe

Returns:

True if running motionbuilder.exe

Return type:

bool

isInHoudini(executable=None)

Determines if the current running executable is houdini.exe

Returns:

True if running houdini.exe

Return type:

bool

isInBlender(executable=None)

Determines if the current running executable is blender

Returns:

True if running blender.exe

Return type:

bool

application()

Returns the currently running application

Returns:

returns one of the following: maya 3dsmax motionbuilder houdini standalone

Return type:

str

machineInfo()

Returns basic information about the current pc that this code is running on

Returns:

{‘OSRelease’: ‘7’,

’OSVersion’: ‘Windows-7-6.1.7601-SP1’, ‘executable’: ‘C:Program FilesAutodeskMaya2018binmaya.exe’, ‘machineType’: ‘AMD64’, ‘node’: ‘COMPUTERNAME’, ‘processor’: ‘Intel64 Family 6 Model 44 Stepping 2, GenuineIntel’, ‘pythonVersion’: ‘2.7.11 (default, Jul 1 2016, 02:08:48) [MSC v.1900 64 bit (AMD64)]’, ‘syspaths’: list(str), ‘env’: dict(os.environ) }

Return type:

dict

user(lower=True)

Returns the current user name

Parameters:

lower (bool) – if the username should be returned as lowercase

Return type:

str

isMac()
Return type:

bool

isWindows()
Return type:

bool

isLinux()
Return type:

bool

isUnixBased()

Is unix based (Linux or Mac)

Returns:

Return type:

bool

currentOS()

Gets current operating system

Returns:

Operating system as string

Return type:

str

isPy3()

Is python 3 or greater

Returns:

bool

Return type:

bool

addToSysPath(path)

Add the specified path to the system path.

Parameters:

path (str) – Path to add.

Returns:

True if path was added. False if path does not exist or path was already in sys.path.

Return type:

bool

Filesystem And Paths

ensureFolderExists(path, permissions=509, placeHolder=False)

if the folder doesn’t exist then one will be created. Function built due to version control mishaps with uncommitted empty folders, this folder can generate a placeholder file.

Parameters:
  • path (str) – the folder path to check or create

  • permissions (int) – folder permissions mode

  • placeHolder (bool) – if True create a placeholder text file

Raises:

OSError – raise OSError if the creation of the folder fails

loadJson(filePath)

This procedure loads and returns the data of a json file

Return type{dict}:

the content of the file

Return type:

Dict[str, Any]

saveJson(data, filepath, **kws)

This procedure saves given data to a json file

Parameters:
  • data (dict) – The json compatible dict to save

  • filepath (str) – The absolute file path to save the data too.

  • kws (Any) – Json Dumps arguments , see standard python docs

zipdir(directory, outputPath, filters=())

Creates a zip file from a given directory recursively.

Use ‘filters’ to supply a fnmatch expression to exclude a directory or files.

Parameters:
  • directory (str) – The directory to save to .zip

  • outputPath (str) – The .zip output path

  • filters (tuple(str)) – A tuple of fnmatch compatible filters.

Returns:

True if the zip was created

Return type:

bool

patchUserHomeRootPath(rootPath)

Patch for zootools preferences path with the use of “~” where python now prioritizes USERPROFILE over HOME which happens to affect maya 2022 and below which sets the USERPROFILE to ~/Documents but maya 2023 is set to ~/ so this patches it globally across zoo only if “~” is the first character and it’s windows ensuring that the existing prefs and updating/new installations are maintained.

Parameters:

rootPath (str) – The root path to patch

Returns:

The patched root path

Return type:

str

findFirstInPaths(filename, paths)

given a filename or path fragment, this will return the first occurrence of a file with that name in the given list of search paths

findFirstInEnv(filename, envVarName)

given a filename or path fragment, will return the full path to the first matching file found in the given env variable

findFirstInPath(filename)

given a filename or path fragment, will return the full path to the first matching file found in the PATH env variable

findInPyPath(filename)

given a filename or path fragment, will return the full path to the first matching file found in the sys.path variable

iterParents(path)

Generator function which iterates each parent folder.

Parameters:

path (str) – The path to iterate

Returns:

Generator[str]

Return type:

str

relativeTo(root, b)

Returns the relative path without “..”

Parameters:
  • root (str) – The main path root path

  • b (str) – The child path which contains the root.

Returns:

the relative path

Return type:

str

Example:

relativeTo(“C:/test/”, “C:/test/hello”) # /hello

filesInDirectory(directory, ext=True)

Returns all files in directory

Parameters:
  • directory (str) – The absolute directory path.

  • ext (bool) – If False then file names without the extension will be returned.

Returns:

a list of file names/

Return type:

list[str]

filesByExtension(directory, extensionList, sort=True)

Lists all of the files inside of the given directory given a file extension list

Extension should be without the fullstop ie [“zooScene”, “json”, “jpg”]

Return Example:

[“soft_sunsetSides.zooScene”, “sun_redHarsh.zooScene”, “sun_warmGlow.zooScene”]

Parameters:
  • directory (str) – The directory to search and return filenames

  • extensionList (list of basestring) – A list of extensions to search [“zooScene”, “json”, “jpg”]

  • sort (bool) – Sort the return list

Return fileList:

A list of files returned that are in the directory and match the extension list

Rtype fileList:

list()str

directories(directory, absolute=False, sort=True)

Get all directories in directory.

Parameters:
  • directory (str) – Directory to look into.

  • absolute (bool) – Gets the function to return the full path or just the dir name.

  • sort (bool) – Sort the directories.

Returns:

Returns list of directory names eg [‘first_dir’, ‘second_dir’] if absolute=True it will return the full path. eg [‘D:/path/to/first_dir’, ‘D:/path/to/second_dir’].

Return type:

list[str]

getExtension(filepath)

Returns the extension of a file path

Parameters:

filepath (basestring) – The full path to a file with extension

Returns:

the extension

Return type:

basestring

getFilesNoExt(directory, fileNoExtension)

Given a file without an extension, find the file name

Useful for finding a thumbnail image with unknown extension, ie could be .jpg or .png

Parameters:
  • directory (str) – The directory to search and return filenames

  • fileNoExtension (str) – The name of the file/s to look for

Return fileList:

List of files matching the name, could be empty or multiple

Rtype fileList:

list(str)

getTexturesNames(textures, input='zbrush', output='mari', prefix=None)

Renames given textures.

Parameters:
  • textures (list) – Textures.

  • input (str) – Input format ( “mari”, “mudbox”, “zbrush” ).

  • output (str) – Output format ( “mari”, “mudbox”, “zbrush” ).

  • prefix (str) – Rename prefix.

Returns:

Converted textures names.

Return type:

list

getTexturesNames(["Diffuse_u0_v0.exr", "Diffuse_u9_v0.exr"])
#[(u'Diffuse_u0_v0.exr', u'Diffuse_1001.exr'), (u'Diffuse_u9_v0.exr', u'Diffuse_1010.exr')]
getTexturesNames(["Diffuse_u0_v0.exr", "Diffuse_u9_v0.exr"], "zbrush", "mudbox")
#[(u'Diffuse_u9_v0.exr', u'Diffuse_u10_v1.exr'), (u'Diffuse_u0_v0.exr', u'Diffuse_u1_v1.exr')]
getTexturesNames(["Diffuse_1001.exr", "Diffuse_1010.exr"], "mari", "zbrush")
#[(u'Diffuse_1001.exr', u'Diffuse_u0_v0.exr'), (u'Diffuse_1010.exr', u'Diffuse_u9_v0.exr')]
getTexturesNames(["Diffuse_1001.exr", "Diffuse_1010.exr"], "mari", "mudbox")
#[(u'Diffuse_1001.exr', u'Diffuse_u1_v1.exr'), (u'Diffuse_1010.exr', u'Diffuse_u10_v1.exr')]
getTexturesNames(["Diffuse_u0_v0.exr", "Diffuse_u9_v0.exr"], prefix="")
#[(u'Diffuse_u0_v0.exr', u'1001.exr'), (u'Diffuse_u9_v0.exr', u'1010.exr')]
getTexturesNames(["Diffuse_u0_v0.exr", "Diffuse_u9_v0.exr"], prefix="Color_")
#[(u'Diffuse_u0_v0.exr', u'Color_1001.exr'), (u'Diffuse_u9_v0.exr', u'Color_1010.exr')]
patchFromUdim(udim)

Returns the patch from given udim.

Parameters:

udim (tuple) – Udim to convert.

Returns:

Patch.

Return type:

int

patchFromUdim((0, 0))
#1001
udimFromPatch(patch)

Returns the udim from given patch.

Parameters:

patch (int) – Patch to convert.

Returns:

Udim.

Return type:

tuple(int,int)

udimFromPatch(1001)
#(0, 0)
getFrameSequencePath(path, frameSpec=None)

Converts the given path with the frame number into a sequence path using the frameSpec value. If not frameSpec then it will default to ‘%4d’

Parameters:
  • path (str) – The path with a frame number

  • frameSpec (str) – The frame specification to replace the frame number with.

Returns:

The full sequence path

Return type:

str

getFileNameNoExt(path)

Get File Name with extension removed “C:/Program Files/HelloWorld.py” ==> “HelloWorld”

Parameters:

path

Returns:

Return type:

getVersionNumber(path)

Extract a version number from the supplied path.

Parameters:

path (str) – The path to a file, likely one to be published.

Returns:

An integer representing the version number in the supplied path. If no version found, None will be returned.

Return type:

int

getVersionNumberAsStr(path)
getImageNoExtension(directory, nameNoExtension)

Returns a list of images with the name (with no file extension) in a directory,

Useful for finding say “thumbnail.png or thumbnail.jpg”

Returns a list of the files found

Parameters:
  • directory (str) – the full path directory to search for files

  • nameNoExtension (str) – the filename with no file extension

Return imagePathList:

a list of images matching the nameNoExtension

Rtype imagePathList:

list

isImage(path)
imageSupportByQt(path)
withExtension(path, extension)

Ensures the provided path endswith the extension.

If the provide path endswith the extension the original path will be returned.

Parameters:
  • path (str) – the file path to ensure an extension exists

  • extension (str)

Returns:

the return Path with extension.

Return type:

str

normpath(path)

Normpath that works in windows and mac

Parameters:

path (str)

Returns:

Return type:

str

Processes

exception SubprocessError(cmd, returnCode)

Bases: Exception

subprocessCheckOutput(*args, **kwargs)

called subprocess.Popen with communicate()

Parameters:
  • args (tuple) – subprocess.Popen arguments

  • kwargs (dict) – subprocess.Popen keyword arguments

Returns:

str output from subprocess.Popen.communicate

Return type:

str

checkOutput(*args, **kwargs)

Helper function that handles sub processing safely on win32 which requires extra flags

Parameters:
  • args (list) – The arguments to pass to subprocess

  • kwargs (dict) – The keyword arguments to pass to subprocess

Returns:

The subprocess output string

Return type:

str

Python Helpers

class Singleton

Bases: type

Singleton metaclass that overrides the __call__ method and always returns a single class instance of the cls.

class ObjectDict

Bases: dict

Wrapper of the standard python dict operate like an object.

a = ObjectDict({'channelBox': False,
         'default': u'',
         'isDynamic': True,
         'keyable': False,
         'locked': False,
         'max': None,
         'min': None,
         'name': u'id',
         'softMax': None,
         'softMin': None,
         'Type': 13, # type found from zoo.libs.maya.api.attrtypes
         'value': u'mid'}
         )
a.max
a.min

This module deals with module paths, importing and the like.

importModule(modulePath, name=None)

Imports the modulePath, if ModulePath is a dottedPath then the function will use importlib otherwise it’s expected that modulePath is the absolute path to the source file. If the name arg is not provided then the basename without the extension will be used.

Parameters:
  • modulePath (str) – The module path either a dottedPath eg. zoo.libs.utils.zoomath or a absolute path.

  • name (str) – The name for the imported module which will be used if the modulepath is a absolute path.

Returns:

The imported module object

Return type:

ModuleObject

validModulePath(path, exclude=None)

Determines if the path is a valid python module path. The python must be ending with either .py or .pyc and not be in the exclude list provide nor in the MODULE_EXCLUDE_PREFIXES.

Parameters:
  • path (str) – The file path to check.

  • exclude (list[str]) – File name prefixes or file base names to exclude.

Return type:

bool

iterModules(path, exclude=None)

Iterate of the modules of a given folder path

Parameters:
  • path (str) – str, The folder path to iterate

  • exclude (List[str] | None) – list, a list of files to exclude

Returns:

iterator

Return type:

Iterator[str]

iterMembers(module, predicate=None)

Iterates the members of the module, use predicte to restrict to a type

:param module:Object, the module object to iterate :param predicate: inspect.class :return:iterator

isDottedPath(path)

Determines if the path is a dotted path. Bit of a hack

Parameters:

path (str) – str

Returns:

bool

Return type:

bool

iterSubclassesFromModule(module, classType)

Iterates all classes within a module object returning subclasses of type classType.

Parameters:
  • module (module object) – the module object to iterate on

  • classType (object) – The class object

Returns:

genertor function returning class objects

Return type:

generator(object)

asDottedPath(path)

Returns a dotted path relative to the python path.

import sys
currentPath = os.path.expanduser("someRandomPath")
sys.path.append(currentPath)
asDottedPath("someRandomPath/subfolder/subsubfolder.py")
#result: subfolder.subsubfolder
Parameters:

path (str) – the absolute path to convert to a dotted path

Returns:

The dotted path relative to the python

Return type:

str

runScriptFunction(filePath, funcName, message, *args)

Runs a function in the provided python script.

Parameters:
  • filePath (str) – The full path to the python script.

  • funcName (str) – The function name within the script to run.

  • message (str) – The debug message to print before the function is run.

  • args (tuple) – The arguments to pass to the function which will be executed.

Returns:

The function return value or None.

Return type:

Any

camelToNice(strInput, space=' ')

Camel case to nicely formatted string

eg. theQuickBrownFox ==> the Quick Brown Fox

Parameters:
  • strInput (str) – String to convert

  • space (str) – The separator string, defaults to “ “

Returns:

Combined string of the separator and the formatted string

Return type:

str

titleCase(strInput)

Turn to title case

Parameters:

strInput (str)

Returns:

The resulting title case of a camel case string

Return type:

str

newLines(text)

Get new lines

Parameters:

text (str)

Returns:

Return type:

int

isStr(text)

If text is a string

Parameters:

text (object) – Text to check if its a string

Returns:

is String

Return type:

bool

fileSafeName(text, spaceTo=' ', keep=(' ', '_', '-'))

Converts string to file safe name

Parameters:
  • keep (tuple or list) – Characters to keep in the name

  • spaceTo (str) – Convert spaces to the following text.

Returns:

Return type:

str

wordWrapPath(path, length=50)

Format the path and add new lines. Mostly used for showing the path nicely in widgets Only for backslashes as it doesn’t do this properly for windows/backslashes

From: C:UsersDocumentszoo_preferencesassetsmaya_scenesNew_Project2scenesmayaScene.ma

to: C:UsersDocumentszoo_preferencesassetsmaya_scenes... …New_Project2scenesmayaScene.ma

Parameters:
  • path (str) – The path to wordwrap

  • length (int) – The number of characters before moving the text into the new line

Returns:

Return type:

str

shortenPath(path, length=50)

Truncates the inner path first depending on length

C:helloworldFinalPath C:...orldFinalPath C:...FinalPath todo: untested on linux/mac

Parameters:
Returns:

Return type:

str

trailingNumber(name)

Returns the trailing number of a string, the name with the number removed, and the padding of the number

Examples:

"shaderName" returns "shaderName", None, 0
"shaderName2" returns "shaderName", 2, 1
"shader1_Name04" returns "shader1_Name", 4, 2
"shaderName_99" returns "shaderName_", 99, 2
"shaderName_0009" returns "shaderName_", 9, 4
Parameters:

name (str) – The string name incoming

Return nameNumberless:

The name now with the number removed, will be the same if no number found

Rtype nameNumberless:

str

Return number:

the number if one exists, will be None if no number finishes the string

Rtype number:

int

Return padding:

the padding of the number

Rtype padding:

int

incrementName(name)

Increment Name

Examples

“obj” –> “obj1” “obj2” –> “obj3” “obj_5” –> “obj_5” “obj_02” –> “obj_03”

Parameters:

name (str) – the name to increment

Returns:

The new name

Return type:

str

findNonAscii(fn)
isAscii(fn)

This module provides handling of version strings i.e. 1.0.0

incrementVersion(versionStr, level)

Increment the major, minor, patch, or alpha/beta version of a version string.

Parameters:
  • versionStr – The version string to be incremented.

  • level – The level of the version to increment. One of “major”, “minor”, “patch”, or “alphaBeta”.

Returns:

The new version string.

Return type:

Raises:

ValueError – If an invalid level is provided.

..code-block python:

versionStr = “0.9.0” newVersion = version.incrementVersion(versionStr, “major”) # Increment major version print(newVersion) # Output: “1.0.0”

versionStr = “0.9.0alpha0” newVersion = version.incrementVersion(versionStr, “patch”) # Increment patch version print(newVersion) # Output: “0.9.1alpha0”

Logging

class CentralLogManager(*args, **kwargs)

Bases: object

This class is a singleton object that globally handles logging, any log added will managed by the class.

addHandler(loggerName, handler)
Parameters:
addLog(logger)

Adds logger to this manager instance

Parameters:

logger (logging.Logger) – the python logger instance.

addNullHandler(loggerName)

Add a null handler to the logger with the specified name.

Parameters:

loggerName (str) – The name of the logger to which the handler will be added.

Returns:

The null handler object that was added to the logger.

Return type:

logging.NullHandler or None

addRotateHandler(loggerName, filePath)

Add a rotating file handler to the logger with the specified name.

Parameters:
  • loggerName (str) – The name of the logger to which the handler will be added.

  • filePath (str) – The path to the log file to which the handler will write.

Returns:

The file handler object that was added to the logger.

Return type:

logging.handlers.RotatingFileHandler or None

addShellHandler(loggerName)

Add a stream handler to the logger with the specified name that outputs to the shell.

Parameters:

loggerName (str) – The name of the logger to which the handler will be added.

Returns:

The stream handler object that was added to the logger.

Return type:

logging.StreamHandler or None

changeLevel(loggerName, level)

Changes the logger instance level.

Parameters:
  • loggerName (str) – The logger instance name.

  • level (int) – eg. logging.DEBUG.

removeHandlers(loggerName)
removeLog(loggerName)

Remove’s the logger instance by name

Parameters:

loggerName (str) – The logger instance name.

Type:

loggerName: str

getLogger(name)

Returns the Zoo tools log name in the form of ‘zootools.*.*’

This is to ensure consistent logging names across all applications

Parameters:

name (str) – The logger name to format.

Returns:

Return type:

logging.Logger

globalLogLevelOverride(logger)

Override a logger’s logging level with the value of an environment variable.

Parameters:

logger (logging.Logger) – The logger object to override the logging level for.

isGlobalDebug()

Returns whether the zootools logging level is set to DEBUG.

Return type:

bool

iterLoggers()

Iterates through all zootools loggers.

Returns:

generator(str, logging.Logger)

Return type:

Iterator[Tuple[str, Logger]]

levelsDict()

Returns the stdlib logging levels as a dict.

The keys are the formal logging names and values are the logging constant value.

Return type:

dict[str: int]

logLevels()

Returns a Map of stdlib logging levels.

Return type:

Iterable[str]

reloadLoggerHierarchy()

Reload the hierarchy of the logging system by removing and re-adding loggers to their parents.

rootLogger()

Retrieves the top most zootools logger instance in the zoo hierarchy

setGlobalDebug(state)

Toggles the root zoo tools logger between DEBUG and INFO

This flush module is a hardcore deletion of modules that live in sys.modules dict

flushUnder(dirPath)

Flushes all modules that live under the given directory.

..note: You must call gc.collect() after calling this function to ensure python garbage collects the modules.

Parameters:

dirPath (str) – the name of the top most directory to search under.

reloadZoo()

Reload all zoo modules from sys.modules This makes it trivial to make changes to plugin that have potentially complex reload dependencies.

import flush;flush.reloadZoo()

The above will force all zoo modules to be reloaded by loops over all base packages path in the environment variable “ZOO_BASE_PATHS” then calling flushUnder(basePath)

Profiling

Python profiling tools

profileit(name)

cProfile decorator to profile said function, must pass in a filename to write the information out to use RunSnakeRun to run the output

Parameters:

name (str) – The output file path

Returns:

Function

Return type:

Callable

profileItEnv(func)

cProfile decorator to profile said function, must pass in a filename to write the information out to use RunSnakeRun to run the output

Uses the environment variables ZOO_PROFILE and ZOO_PROFILE_PATH to determine if profiling should be run and where to output the file to.

Returns:

Function

Return type:

Callable

fnTimer(function)