Utilities

Application

mainWindow()
quit()
saveScene()
restart(force=False, delay=3)

Colour

Colors

This module contains functions related to color but not specific to any particular software

from zoo.libs.utils import color

convertHsvToRgb(hsv)

Converts hsv values to rgb rgb is in 0-1 range srgbFloat, hsv is in (0-360, 0-1, 0-1) ranges

Parameters

hsv (list or tuple) – Hue Saturation Value Hue is in 0-360 range, Sat/Value 0-1 range

Return rgb

Red Green Blue values 0-1 srgbFloat

Rtype rgb

list

convertRgbToHsv(rgb)

Converts rgb values to hsv rgb is in 0-1 range, hsv is in (0-360, 0-1, 0-1) ranges

Parameters

rgb (list or tuple) – Hue Saturation Value Hue is in 0-360 range, Sat/Value 0-1 range

Return hsv

Red Green Blue values 0-1

Rtype hsv

list

convertSingleSrgbToLinear(colorValue)

Changes a single rgb color (so say red only) to linear space.

Parameters

colorValue (float) – a single color value, expects a value from 0-1

Return Linear

the new color converted to linear

Rtype Linear

float

convertSingleLinearToSrgb(colorValue)

Changes a single rgb color (so say red only) in linear so the resulting color is displayed in srgb color space.

Parameters

colorValue (float) – a single color value, expects a value from 0-1

Return Srgb

the new color converted to srgb

Rtype Srgb

float

convertColorSrgbToLinear(srgbColor)

Changes a srgb color to linear color

Parameters

srgbColor (list of floats) – a SRGB float color list/tuple, expects values from 0-1

Return linearRgb

the new color gamma converted to linear

Rtype linearRgb

float

convertColorLinearToSrgb(linearRgb)

Changes a linear color to srgb color

Parameters

linearRgb (list of floats) – a rgb color list/tuple, expects values from 0-1

Returns

the new color gamma converted to srgb

Return type

tuple(float)

convertSrgbListToLinear(srgbList, roundNumber=True)

Converts a list to linear, optional round to 4 decimal places

Parameters
  • srgbList (list) – list of srgb colors range 0-1 eg (0.0, 1.0, 0.0)

  • roundNumber (bool) – do you want to round to 4 decimal places?

Return linearRgbList

The list of colors converted to linear color

Rtype linearRgbList

list

desaturate(col, level=1.0)

Returns a desaturated color

Parameters
  • col (tuple) – int color tuple eg (128, 128, 255, 255)

  • level (float) – Level of desaturation from 0 to 1.0. 1.0 is desaturated, 0 is the same saturation

Returns

Tuple with desaturated color

Return type

tuple

offsetHueColor(hsv, offset)

Offsets the hue value (0-360) by the given offset amount keeps in range 0-360 by looping Max offset is 360, min is -360

Parameters
  • hsv (list) – The hue sat val color list [180, .5, .5]

  • offset (float) – How much to offset the hue component, can go past 360 or less than 0. 0-360 color wheel

Return hsv

The new hsv list eg [200, .5, .5]

Rtype hsv

list

offsetSaturation(hsv, offset)

Offsets the “saturation” value (0-1) by the given offset amount keeps in range 0-1 by looping

Parameters
  • hsv (list) – a 3 value list or tuple representing a the hue saturation and value color [180, .5, .5]

  • offset (float) – the offset value to offset the color

Return hsv

the hue saturation value color eg [200, .5, .5]

Return type

list

offsetColor(col, offset=0)

Returns a color with the offset in tuple form.

Parameters
  • col (tuple(int,int,int)) – Color in form of tuple with 3 ints. eg tuple(255,255,255)

  • offset – The int to offset the color

Returns

tuple (int,int,int)

offsetValue(hsv, offset)

Offsets the “value” (brightness/darkness) value (0-1) by the given offset amount keeps in range 0-1 by looping

Parameters
  • hsv (list) – a 3 value list or tuple representing the hue, saturation and value color [180, .5, .5]

  • offset (float) – the offset value to offset the color

Return hsv

the hue saturation value color eg [200, .5, .5]

Return type

list

hueShift(col, shift)

Shifts the hue of the given colour

Parameters
  • col (tuple(int,int,int) or tuple(float,float,float)) – Colour to shift. (0.0 to 1.0)

  • shift (int) – The distance and direction of the colour to shift. Plus or minus 1-360

Returns

the colour with the shifted hue

Return type

tuple(int,int,int)

hexToRGBA(hexstr)

Converts hexidecimal number to RGBA tuple

Allows folowing formats:

“RRGGBB” eg 2F2F2F “AARRGGBB” eg 882F2F2F “RGB” eg CCC

Parameters

hex – String hex eg “2F2F2F”

Returns

Returns in format tuple(R, G, B, A)

Return type

tuple

hexToRGB(hexstr)

Converts hexidecimal number to RGBA tuple

Parameters

hex – String hex eg “2F2F2F”

Returns

Returns in format tuple(R, G, B)

Return type

tuple

RGBToHex(rgb)

Converts rgb tuple to hex string

(62, 104, 173) ==> ‘3E68AD’ (168, 20, 86, 255) ==> ‘FF3E68AD’

Parameters

rgb – rgb tuple

Returns

Hex string eg ‘44FF33’

rgbIntToFloat(color)

Turns int color (255,255,255,255) to (1.0, 1.0, 1.0, 1.0)

Parameters

color – int color tuple eg (128, 128, 255, 255)

Returns

Float color eg (0.5, 0.5, 1.0, 1.0)

rgbFloatToInt(color)

Turns float color to int color eg (1.0, 1.0, 1.0, 1.0) to (255,255,255,255)

Parameters

color – float color tuple eg (0.5, 0.5, 1.0, 1.0)

Returns

int color eg (128, 128, 255, 255)

rgbIntRound(color)

Rounds all values of 255 color

example:

(244.9, 100, 10.33) is returned as (255, 100, 10)

Parameters

color – int color tuple eg (255.0, 0.001, 0.0)

Type

tuple

Returns

int color converted eg (255, 0, 0)

Return type

tuple

class RGBRotate

Bases: object

Hue Rotation, using the matrix rotation method. From here

https://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color

set_hue_rotation(degrees)
apply(r, g, b)
hslColourOffsetFloat(rgb, hueOffset=0, saturationOffset=0, lightnessOffset=0)

Offset color with hue, saturation and lightness (brighten/darken) values

Colour is expected as rgb in 0.0-1.0 float range eg (0.1, 0.34, 1.0)

Offsets are in:

hue: 0-360,
saturation: 0.0-1.0,
value (lightness): 0.0-1.0

Returned colour is rgb in in 0-1.0 range eg (0.1, 0.34, 1.0)

Parameters
  • rgb (tuple) – the rgb color in 0.0-0.1 range eg (0.1, 0.34, 1.0)

  • hueOffset (float) – the hue offset in 0-360 range

  • saturationOffset (float) – the saturation offset in 0-255 range

  • lightnessOffset (float) – the lightness value offset, lighten (0.2) or darken (-0.3), 0-0.1 range as an offset

Returns

the changed rgb color in 0.0-0.1 range eg (0.1, 0.34, 1.0)

Return type

tuple[float, float, float]

hslColourOffsetInt(rgb, hueOffset=0, saturationOffset=0, lightnessOffset=0)

Offset color with hue, saturation and lightness (brighten/darken) values Colour is expected as rgb in 0-255 range eg (255, 123, 23)

Offsets are in:

hue: 0-360,
saturation: 0-255,
value (lightness): 0-255

Returned colour is rgb in in 0-255 range eg (255, 123, 23)

Parameters
  • rgb (tuple) – the rgb color in 0-255 range eg (255, 123, 23)

  • hueOffset (int) – the hue offset in 0-360 range

  • saturationOffset (int) – the saturation offset in 0-255 range

  • lightnessOffset (int) – the lightness value offset, lighten (30) or darken (-30), 0-255 range as an offset

Returns

the changed rgb color in 0-255 range eg (255, 123, 23)

Return type

tuple[int, int, int]

hsv2rgb(hue, sat, value)

HSV to rgb. Takes in a hue from 0-360. todo might be the same as convertHsvToRgb

Parameters
  • hue – Hue

  • sat

  • value

Returns

convertKelvinToRGB(colour_temperature)

Converts from K to RGB, algorithm courtesy of http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/

Parameters

colour_temperature (float) – the color in degrees kelvin

Returns

srgb color in int 255 format

Rtype srgb

tuple(int)

generateHueOffsetPalette(startHsvColor, colorNumber=20, hueRange=280.0)

Generates a color palette by offsetting the hue value from a start hsv color (0-360.0, 0-1.0, 0-1.0)

Parameters
  • startHsvColor (tuple[float]) – The first color in the palette in hsv color (0-360.0, 0-1.0, 0-1.0)

  • colorNumber (int) – The total number of colors in the palette

  • hueRange (float) – The full spectrum range of the entire color palette in the hue range (360.0 is a full circle)

Return colorListSrgb

A color list in rgb float [0-1.0, 0-1.0, 0-1.0]

Rtype colorListSrgb

tuple

Constants

Commandline

class CommandProgressBar(total, prefix, suffix, decimals=1, barLength=50)

Bases: object

increment(value=0)
start()

Filesystem

clearUnMasked(func)

Decorator which clears the umask for a method. The umask is a permissions mask that gets applied whenever new files or folders are created. For I/O methods that have a permissions parameter, it is important that the umask is cleared prior to execution, otherwise the default umask may alter the resulting permissions

upDirectory(path, depth=1)

Walks up the directory structure, use the depth argument to determine how many directories to walk

Parameters
  • path (str) – the starting path to walk up

  • depth (int) – how many directories to walk

Returns

the found directory

Return type

str

iterParentPath(childPath)

Generator function that walks up directory structure starting at the childPath

Parameters

childPath (str) – the starting path to walk up

Return type

generator(str)

findParentDirectory(childPath, folder)

recursively walks the up the directory structure and returns the first instance of the folder

Parameters
  • childPath (str) – the childpath to walk up

  • folder (str) – the folder name to find.

Returns

the first instance of folder once found.

Return type

str

openLocation(path)

Opens the parent directory of a file, selecting the file if possible.

Note

needs to be tested in win 10 from inside of Maya, current issues

Parameters

path (str) – the path to the directory or file.

openDirectory(directoryPath)

Opens the native OS folder to the directory of file name similar to os.startfile(filename) but also supporting osx and linux.

Note

current duplicate of findParentDirectory() Just it is not working from Maya, needs to be fixed.

Parameters

directoryPath (str) – the path to the directory to open

copyFile(src, dst, permissions=509)

Copy file and sets its permissions.

Parameters
  • src – Source file

  • dst – destination

  • permissions – Permissions to use for target file. Default permissions will be readable and writable for all users.

retainCwd()

Context manager that keeps cwd unchanged afterwards.

setCwd(cwd)

Slightly different version to retainCwd that accepts a parameter

Parameters

cwd

Returns

batchCopyFiles(paths, permissions=509)

Expects the parent folder to have been already created.

Parameters
  • paths (tuple(tuple(str, str))) – source path, destination path

  • permissions (int) – OS permissions

Returns

a list of tuples containing source,destination fails

Return type

list(tuple(str, str)

copyDirectory(src, dst, ignorePattern=None)

Copies the directory tree using shutil.copytree

Parameters
  • src (str) – the Source directory to copy.

  • dst (str) – the destination directory.

Raise

OSError

copyDirectoryContents(src, dst, skipExist=True, overwriteModified=False)

Copies the contents of one directory to another including sub-folders. Will make the destination directory if it doesn’t exist Kwargs for checking if the file already exists or has been modified

Parameters
  • src (str) – The source path a directory path

  • dst (str) – The destination path, a directory path, will create if it does not exist

  • skipExist (bool) – If True will skip if the file already exists

  • overwriteModified (bool) – If the file exists but has been modified overwrite

class MoveFileContext

Bases: object

With context utility to ensures that files that were moved within the scope are moved to their original location if an exception was raised during that scope.

with MoveFileContext() as FileContext:
    someSourcePath = os.path.expandUser("~/soemfile.config")
        FileContext.move(sourceSourcePath, os.path.join(os.path.dirname(sourcePath), "destination.config"))
        ValueError("raise an error, so we revert")
move(source, destination)

Move’s a file and keeps track of the source/destination if it succeeded.

Parameters
  • source – Source file to move.

  • destination – New location for that file.

folderSize(path)

Retrieves the total folder size in bytes

Parameters

path (str) – Returns the total folder size by walking the directory adding together all child files sizes.

Returns

size in bytes

Return type

int

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

If the folder doesnt exist then one will be created. Function built due to version control mishaps with uncommitted empty folders, this folder can generate a place holder file.

Parameters
  • path (str) – the folderpath 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

createValidfilename(name)

Sanitizer for file names which everyone tends to screw up, this function replace spaces and random character with underscore.

createValidFilename("Some random file name")
#result: "Some_random_file_name"
Parameters

name (str) – the name to convert

Return type

the same format as the passed argument type(utf8 etc)

zipwalk(zfilename)

Zip file tree generator.

For each file entry in a zip archive, this yields a two tuple of the zip information and the data of the file as a StringIO object.

zipinfo, filedata

zipinfo is an instance of zipfile.ZipInfo class which gives information of the file contained in the zip archive. filedata is a StringIO instance representing the actual file data.

If the file again a zip file, the generator extracts the contents of the zip file and walks them.

Inspired by os.walk .

directoryTreeToDict(path)
loadJson(filePath, **kwargs)

This procedure loads and returns the data of a json file

Return type{dict}

the content of the file

saveJson(data, filepath, message=True, **kws)

This procedure saves given data to a json file

Parameters
  • data (dict) – The dictionary to save

  • filepath (str) – The full filepath of the json file

  • message (bool) – Report the message to the user?

  • kws – Json Dumps arguments , see standard python docs

Return success

File written?

Rtype success

bool

loadFile(filepath)
getTempDir()

Returns the temp directory path on all OS

Return directory

The temp directory full path

Rtype directory

str

moveFile(fromFullPath, toFullPath)

Moves a file (cut place) from one location to another

Parameters
  • fromFullPath (str) – Full path to the file

  • toFullPath (str) – Full path to the destination

loadFileTxt(filePath)

Loads a file as text

Parameters

filePath (str) – the absolute file path

Return textFile

the text file

Rtype textFile

str

saveFileTxt(formattedText, newfile)

Saves a string to a file

Parameters
  • formattedText (str) – the text

  • newfile (str) – the file to be saved full path

createZipWithProgress(zippath, files)

Same as function createZip() but has a stdout progress bar which is useful for commandline work :param zippath: the file path for the zip file :type zippath: str :param files: A Sequence of file paths that will be archived. :type files: seq(str)

createZip(zippath, files)

Creates a zip file for the files, each path will be stored relative to the zippath which avoids abspath :param zippath: the file path for the zip file :type zippath: str :param files: A Sequence of file paths that will be archived. :type files: seq(str)

checkWritableFile(fullPathFileOrDir)

Checks the write-ablity when file permissions can’t be checked. Tries to rename file to the exact same name.

Usually errors when file is in use by the OS.

This function is currently a hack, if error the file is not writable.

Parameters

fullPathFileOrDir (str) – the fullpath to the file or the directory

Return fileInUseError

returns as True if any file is writable

Rtype fileInUseError

str

checkWritableFiles(fileFullPathList)

Checks the write-ablity when file permissions can’t be checked. Tries to rename files to the exact same name

The file may be in use by a program and cannot be modified, is tricky to catch without the rename hack

Returns error as True if any files in the list aren’t writable

Parameters

fileFullPathList (list(str)) – a list of fullpaths to the files or the directories

Return fileInUseError

returns as True if any files in the list aren’t writable

Rtype fileInUseError

bool

uniqueFileName(fullFilePath, countLimit=500)

Finds a unique filename if a name already exists by adding a number to the end of the file

See trailingNumber() documentation for how the numerical numbers are added to the tail of the name.

Parameters
  • fullFilePath (str) – Any full path to a filename with an extension

  • countLimit (int) – since this function uses a while loop, set a limit of loops to stop infinite.

Return fullFilePath

The new fullFilePath possibly renamed if matching filename already exists. “” if count hit

Rtype fullFilePath

str

renameMultipleFilesNoExt(newNameNoExtension, fileFullPathToRenameList, skipThumbnails=True)

Rename multiple files/dependency folders useful for .zooScene files and check if all files can be renamed first.

Files may be in use by a program and cannot be modified, is tricky to catch without the rename hack A file may be in use, for example alembic files renaming in the wrong order will cause issues.

If errors then no files will be renamed.

Parameters
  • newNameNoExtension (str) – the new name of the files with no extension, no directory path, filename only

  • fileFullPathToRenameList (list(str)) – a list of fullpaths to the files or the directories

  • skipThumbnails (bool) – Skips files named thumbnails, “thumbnail.jpg” or “thumbnail.png”

Return renamedList

the renamed files full file path, if empty it’s failed

Rtype renamedList

str

Flush

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)

reloadHard(moduleName)

Removes all modules from sys that starts with the module name

Parameters

moduleName (str) – The module name to remove

General

merge(a, b, onlyMissingKeys=False, path=None)

Merges two dicts http://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge/7205107#7205107

clearList(l)

Clears list while keeping the reference

Parameters

l

Returns

getArgs(localDict)

Get args from local dict

Returns

numericalSort(data)

Numerically sorts a list of strings that may have integers within

Return type

list(str)

data = ["ctrl1", "ctrl50", "ctrl2", "ctrl"]
print numericalSort(data)
# Result: ['joint', 'joint1', 'joint2', 'joint50'] #
humanizeBytes(bytes, precision=1)

Return a humanized string representation of a number of bytes. Based on: http://code.activestate.com/recipes/577081-humanized-representation-of-a-number-of-bytes

humanize_bytes(1)
# '1 byte'
humanizeBytes(1024)
# '1.0 kB'
humanizeBytes(1024*123)
# '123.0 kB'
humanizeBytes(1024*12342)
# '12.1 MB'
humanizeBytes(1024*12342,2)
# '12.05 MB'
humanizeBytes(1024*1234,2)
# '1.21 MB'
humanizeBytes(1024*1234*1111,2)
# '1.31 GB'
humanizeBytes(1024*1234*1111,1)
# '1.3 GB'
getDuplicates(seq)

Return’s all the duplicate value in seq

Parameters

seq (list or tuple) – the sequence of possible duplicates

Returns

a list of duplicate values from seq

Return type

list

fuzzyFinder(input, collection)

A poor person fuzzy finder function.

Parameters
  • input (str.) – A partial string which is typically entered by a user.

  • collection (iterable.) – A collection of strings which will be filtered based on the input.

Returns

A generator object that produces a list of suggestions narrowed down from collection using the input.

Return type

generator.

list(fuzzyFinder("te", ["gete", "test", "hello", "job", "lbsknasdvte", "3rya8d^&%()te)VHF"]))
# result ['test', 'gete', 'lbsknasdvte', '3rya8d^&%()te)VHF']
isIteratable(obj)

Determines if the object is an iterable.

This is done by attempting to iterate on the obj and if it raise’s a type error then return False else True

Returns

returns True if the obj is iterable.

Return type

bool

chunks(iteratable, size, overlap=0)

Yield successive sized chunks from iteratable.

uniqify(li)

Makes list unique (No duplicates), and preserves order

Parameters

li (list) – List to make unique

Returns

Return type

jsonToBool(val)

Returns true or false based on the string given.

Parameters

val (basestring) –

Returns

Return type

bool

printException()

Print out the exception.

Without raising the exception. Should be run in the exception block

Returns

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
compareDictionaries(source, target)

Compare the two dictionaries source and target.

Target will get the new changes from source.

Parameters
  • source (dict) – The source dictionary with the original zoo key entries

  • target (dict) – The target dictionary that will get the new changes from source

Return messageLog

A message log of any changes that have occurred

Rtype messageLog

str

Output

displayInfo(txt)

Display info based on application

Parameters

txt – Info text

Returns

displayWarning(txt)

Display Warning based on application

Parameters

txt – warning

Returns

displayError(txt)

Display Error based on application

Parameters

txt – error

Returns

clearViewMessage(position='botCenter', clear=True)
inViewMessage(txt='Message highlight <hl>highlight</hl>.', position='botCenter', fade=True, textOffset=30, fadeInTime=1, fadeOutTime=1, fadeStayTime=1500, alpha=1.0)

Path

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

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

Returns

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

fnTimer(function)

Thread

class Threaded

Bases: object

Threaded base class that contains a threading.Lock member and an ‘exclusive’ function decorator that implements exclusive access to the contained code using a thread lock.

static exclusive(func)

Static method intended to be used as a function decorator in derived classes.

Parameters

func – Function to decorate/wrap

Returns

Wrapper function that executes the function inside the acquired lock

@Threaded.exclusive
def my_method(self, ...):
    ...
threadedCopy(filepaths)

Copies a set of files in a separate thread.

Uses the CopyThread class.

Parameters

filepaths (list(str)) – is a list of (from_path, to_path) pairs.

paths =[('C:/src/path.txt', 'C:/destination/path.txt'),
('C:/src/path1.txt', 'C:/destination/path1.txt'),
('C:/src/path2.txt', 'C:/destination/path2.txt')]
threadedCopy(paths)
class CopyThread(filepaths)

Bases: threading.Thread

run()

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

Timeutils

formatFrameToTime(start, current, frameRate)
formatModifiedDateTime(dateTime)

Format a data/time into a nice human-friendly string.

Parameters

dateTime (datatime) – The datetime instance to be formatted

:returns A string representing the datetime in a nice format :rtype: str

from datetime import datetime
now = datetime.now()
format_modified_date_time_str(now)
# result: 'Today, 9:23am'
daySuffix(day)

Figure out the suffix to use for the specified day of the month (e.g. 1st, 3rd, 15th, 32nd, etc.)

Parameters

day (int) – The day of the month

Returns

A string containing the shorthand suffix for the day of the month

Return type

str

Zoomath

lerp(current, goal, weight=0.5)
lerpCount(start, end, count)

Iterates between start and goal for the given count.

for i in lerpCount(-10, 10, 8):
    print(i)

Outputs:

# 0.0
# 0.25
# 0.5
# 0.75
# 1.0
Parameters
  • start (float) – The starting number i.e. 0.0

  • end (float) – The goal number i.e. 1.0

  • count (int) – The number of iterations.

Return type

Iterable[float]

remap(value, oldMin, oldMax, newMin, newMax)
almostEqual(x, y, tailCount)
mean(numbers)

Returns the mean/average of the numbers.

Parameters

numbers (list[float]) – The numbers to average.

Return type

float

threePointParabola(a, b, c, iterations)
clamp(value, minValue=0.0, maxValue=1.0)

Clamps a value withing a max and min range

Parameters
  • value (float) – value/number

  • minValue (float) – clamp/stop any value below this value

  • maxValue (float) – clamp/stop any value above this value

Return clampedValue

clamped value as a float

Rtype clampedValue

float

Str Utils

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

Unittest

decorating_meta(decorator)
skipUnlessHasattr(obj)
class BaseUnitest(methodName='runTest')

Bases: unittest.case.TestCase

This Class acts as the base for all unitests, supplies a helper method for creating tempfile which will be cleaned up once the class has been shutdown. If you override the tearDownClass method you must call super or at least clean up the _createFiles set

application = 'standalone'
classmethod createTemp(*args, **kwargs)
classmethod mkstemp(*args, **kwargs)
classmethod mkdtemp(*args, **kwargs)
classmethod addTempFile(filepath)
classmethod tearDownClass()
class ZooTestResult(*args, **kwargs)

Bases: unittest.runner.TextTestResult

startTest(test)

Called when the given test is about to be run

addSuccess(test)

Called when a test has completed successfully

class ZooTestRunner(slowTestThreshold=0.3, *args, **kwargs)

Bases: unittest.runner.TextTestRunner

run(test)

Run the given test case or test suite.

runTests(directories=None, test=None, test_suite=None, buffer=False, failfast=False, stream=None, resultClass=None)

Run all the tests in the given paths.

Parameters
  • directories – A generator or list of paths containing tests to run.

  • test – Optional name of a specific test to run.

  • test_suite – Optional TestSuite to run. If omitted, a TestSuite will be generated.

getTests(directories, test=None, testSuite=None, topLevelDir=None)

Get a unittest.TestSuite containing all the desired tests.

Parameters
  • directories – Optional list of directories with which to search for tests.

  • test – Optional test path to find a specific test such as ‘test_mytest.SomeTestCase.test_function’.

  • testSuite – Optional unittest.TestSuite to add the discovered tests to. If omitted a new TestSuite will be created.

Returns

The populated TestSuite.

Return type

unittest.suite.TestSuite