Utilties

Environment handling

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 – 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

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

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

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 – 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

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

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

iterModules(path, exclude=None)

Iterate of the modules of a given folder path

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

  • exclude – list, a list of files to exclude

Returns:

iterator

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

Returns:

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.

class CentralLogManager(*args, **kwargs)

Bases: object

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

addLog(logger)

Adds logger to this manager instance

Parameters:

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

removeLog(loggerName)

Remove’s the logger instance by name

Parameters:

loggerName – The logger instance name.

Type:

loggerName: str

changeLevel(loggerName, level)

Changes the logger instance level.

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

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

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

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

addHandler(loggerName, handler)
Parameters:
removeHandlers(loggerName)
logLevels()

Returns a Map of stdlib logging levels.

Return type:

Iterable[str]

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]

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.

reloadLoggerHierarchy()

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

iterLoggers()

Iterates through all zootools loggers.

Returns:

generator(str, logging.Logger)

rootLogger()

Retrieves the top most zootools logger instance in the zoo hierarchy

setGlobalDebug(state)

Toggles the root zoo tools logger between DEBUG and INFO

isGlobalDebug()

Returns whether the zootools logging level is set to DEBUG.

Return type:

bool

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

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)

camelToNice(strInput, space=' ')

Camel case to nicely formatted string

eg. theQuickBrownFox ==> the Quick Brown Fox

Parameters:
  • strInput (basestring) – String to convert

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

Returns:

Combined string of the separator and the formatted string

Return type:

basestring

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

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:

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 – The path to wordwrap

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

Returns:

shortenPath(path, length=50)

Truncates the inner path first depending on length

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

Parameters:
  • path

  • length

Returns:

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)