Core

The Toolkit Foundation is the part of the Toolkit Core API that contains lower level components and APIs. These include

  • Automatic folder creation

  • Template system and path resolution APIs

  • Execution of Tank Admin commands

  • The Toolkit Context

  • The Sgtk Main API class

For apps and engines, see the Apps, Engines and Frameworks documentation.

Note

The Toolkit Foundation APIs require that you run them from within an initialized toolkit environment. For more information on how to set this up, see Initialization and startup.

Sgtk

class sgtk.Sgtk(project_path)[source]

The Toolkit Core API. Instances of this class are associated with a particular configuration and contain access methods for a number of low level Toolkit services such as filesystem creation, hooks, context manipulation and the Toolkit template system.

Note

Do not create this instance directly - Instead, instances of this class should be created using the methods sgtk_from_path(), sgtk_from_entity() or via the sgtk.bootstrap.ToolkitManager. For more information, see Initialization and startup.

property configuration_descriptor

The ConfigDescriptor which represents the source of the environments associated with this pipeline configuration.

property bundle_cache_fallback_paths

List of paths to the fallback bundle caches for the pipeline configuration.

property project_path

Path to the default data directory for a project.

Toolkit Projects that utilize the template system to read and write data to disk will use a number of Shotgun local storages as part of their setup to define where data should be stored on disk. One of these storages is identified as the default storage.

Raises:

TankError if the configuration doesn’t use storages.

property roots

Returns a dictionary of storage root names to storage root paths.

Toolkit Projects that utilize the template system to read and write data to disk will use one or more Shotgun local storages as part of their setup to define where data should be stored on disk. This method returns a dictionary keyed by storage root name with the value being the path on the current operating system platform:

{
    "work": "/studio/work/my_project",
    "textures": "/studio/textures/my_project"
}

These items reflect the Local Storages that you have set up in Shotgun.

Each project using the template system is connected to a number of these storages - these storages define the root points for all the different data locations for your project. So for example, if you have a mount point for textures, one for renders and one for production data such as scene files, you can set up a multi root configuration which uses three Local Storages in Shotgun. This method returns the project storage locations for the current project. The key is the name of the local storage as defined in your configuration. The value is the path which is defined in the associated Shotgun Local storage definition for the current operating system, concatenated with the project folder name.

property shotgun_url

The associated shotgun url, e.g. https://mysite.shotgunstudio.com

property shotgun

Just-in-time access to a per-thread Shotgun API instance.

This Shotgun API is threadlocal, meaning that each thread will get a separate instance of the Shotgun API. This is in order to prevent concurrency issues and add a layer of basic protection around the Shotgun API, which isn’t threadsafe.

property version

The version of the tank Core API (e.g. v0.2.3)

property documentation_url

A url pointing at relevant documentation for this version of the Toolkit Core or None if no documentation is associated.

property configuration_mode

The mode of the currently running configuration:

  • sgtk.CENTRALIZED if the configuration is part of a centralized setup.

  • sgtk.DISTRIBUTED if the configuration is part of a distributed setup.

  • sgtk.DEFAULT if the configuration does not have an associated pipeline pipeline configuration but is falling back to its default builtins.

property configuration_name

The name of the currently running Shotgun Pipeline Configuration, e.g. Primary. If the current session does not have an associated pipeline configuration in Shotgun (for example because you are running the built-in integrations), None will be returned.

property configuration_id

The associated Shotgun pipeline configuration id. If the current session does not have an associated pipeline configuration in Shotgun (for example because you are running the built-in integrations), None will be returned.

property templates

A dictionary, where the keys are the template names, and the values are Template instances representing the tokenized paths, as defined in the configuration’s templates.yml.

Returns:

dict

reload_templates()[source]

Reloads the template definitions from disk. If the reload fails a TankError will be raised and the previous template definitions will be preserved.

Note

This method can be helpful if you are tweaking templates inside of for example Maya and want to reload them. You can then access this method from the python console via the current engine handle:

sgtk.platform.current_engine().sgtk.reload_templates()
Raises:

TankError

list_commands()[source]

Lists the system commands registered with the system.

This method will return all system commands which are available in the context of a project configuration will be returned. This includes for example commands for configuration management, anything app or engine related and validation and overview functionality. In addition to these commands, the global commands such as project setup and core API check commands will also be returned.

For more information, see sgtk.list_commands()

Returns:

list of command names

get_command(command_name)[source]

Returns an instance of a command object that can be used to execute a command.

Once you have retrieved the command instance, you can perform introspection to check for example the required parameters for the command, name, description etc. Lastly, you can execute the command by running the execute() method.

In order to get a list of the available commands, use the list_commands() method.

For more information, see sgtk.get_command()

Parameters:

command_name – Name of command to execute. Get a list of all available commands using the list_commands() method.

Returns:

SgtkSystemCommand object instance

templates_from_path(path)[source]

Finds templates that matches the given path:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> tk.templates_from_path("/studio/my_proj/assets/Car/Anim/work")
<Sgtk Template maya_asset_project: assets/%(Asset)s/%(Step)s/work>
Parameters:

path – Path to match against a template

Returns:

list of TemplatePath or [] if no match could be found.

template_from_path(path)[source]

Finds a template that matches the given path:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> tk.template_from_path("/studio/my_proj/assets/Car/Anim/work")
<Sgtk Template maya_asset_project: assets/%(Asset)s/%(Step)s/work>
Parameters:

path – Path to match against a template

Returns:

TemplatePath or None if no match could be found.

paths_from_template(template, fields, skip_keys=None, skip_missing_optional_keys=False)[source]

Finds paths that match a template using field values passed.

This is useful if you want to get a list of files matching a particular template and set of fields. One common pattern is when you are dealing with versions, and you want to retrieve all the different versions for a file. In that case just resolve all the fields for the file you want to operate on, then pass those in to the paths_from_template() method. By passing version to the skip_keys parameter, the method will return all the versions associated with your original file.

Any keys that are required by the template but aren’t included in the fields dictionary are always skipped. Any optional keys that aren’t included are only skipped if the skip_missing_optional_keys parameter is set to True.

If an optional key is to be skipped, all matching paths that contain a value for that key as well as those that don’t will be included in the result.

Note

The result is not ordered in any particular way.

Imagine you have a template maya_work: sequences/{Sequence}/{Shot}/work/{name}.v{version}.ma:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/my_proj")
>>> maya_work = tk.templates["maya_work"]

All fields that you don’t specify will be searched for. So if we want to search for all names and versions for a particular sequence and shot, we can do:

>>> tk.paths_from_template(maya_work, {"Sequence": "AAA", "Shot": "001"})
/studio/my_proj/sequences/AAA/001/work/background.v001.ma
/studio/my_proj/sequences/AAA/001/work/background.v002.ma
/studio/my_proj/sequences/AAA/001/work/background.v003.ma
/studio/my_proj/sequences/AAA/001/work/mainscene.v001.ma
/studio/my_proj/sequences/AAA/001/work/mainscene.v002.ma
/studio/my_proj/sequences/AAA/001/work/mainscene.v003.ma
Parameters:
  • template (TemplatePath) – Template against whom to match.

  • fields (Dictionary) – Fields and values to use.

  • skip_keys (List of key names) – Keys whose values should be ignored from the fields parameter.

  • skip_missing_optional_keys – Specify if optional keys should be skipped if they aren’t found in the fields collection

Returns:

Matching file paths

Return type:

List of strings.

abstract_paths_from_template(template, fields)[source]

Returns an abstract path based on a template.

Similar to paths_from_template(), but optimized for abstract fields such as image sequences and stereo patterns.

An abstract field is for example an image sequence pattern token, such as %04d, %V or @@@@@. This token represents a large collection of files. This method will return abstract fields whenever it can, and it will attempt to optimize the calls based on abstract pattern matching, trying to avoid doing a thousand file lookups for a thousand frames in a sequence.

It works exactly like paths_from_template() with the difference that any field marked as abstract in the configuration will use its default value rather than any matched file values. Sequence fields are abstract by default.

Note

The result is not ordered in any particular way.

Imagine you have a template render: sequences/{Sequence}/{Shot}/images/{eye}/{name}.{SEQ}.exr:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/my_proj")
>>> render = tk.templates["render"]

All fields that you don’t specify will be searched for. So if we want to search for all names and versions for a particular sequence and shot, we can do:

>>> tk.abstract_paths_from_template(maya_work, {"Sequence": "AAA", "Shot": "001"})
/studio/my_proj/sequences/AAA/001/images/%V/render_1.%04d.exr
/studio/my_proj/sequences/AAA/001/images/%V/render_2.%04d.exr
/studio/my_proj/sequences/AAA/001/images/%V/render_3.%04d.exr

Note

There are situations where the resulting abstract paths may not match any files on disk

Take the following template:

render: sequences/{Sequence}/{Shot}/images/{Shot}.{SEQ}.jpg

Assuming Shot is provided via the fields argument, the method will avoid listing all files in the leaf directory since {SEQ} is abstract and {Shot} is known. The following abstract path will be returned even if only the parent images directory exists:

/studio/my_proj/sequences/AAA/001/images/001.%04d.exr
Parameters:
  • template (TemplatePath) – Template with which to search

  • fields (dictionary) – Mapping of keys to values with which to assemble the abstract path.

Returns:

A list of paths whose abstract keys use their abstract(default) value unless a value is specified for them in the fields parameter.

paths_from_entity(entity_type, entity_id)[source]

Finds paths associated with a Shotgun entity.

Note

Only paths that have been generated by create_filesystem_structure() will be returned. Such paths are stored in Shotgun as FilesystemLocation entities.

Parameters:
  • entity_type – a Shotgun entity type

  • entity_id – a Shotgun entity id

Returns:

Matching file paths

Return type:

List of strings.

entity_from_path(path)[source]

Returns the shotgun entity associated with a path.

Note

Only paths that have been generated by create_filesystem_structure() will be returned. Such paths are stored in Shotgun as FilesystemLocation entities.

Parameters:

path – A path to a folder or file

Returns:

Shotgun dictionary containing name, type and id or None if no path was associated.

context_empty()[source]

Factory method that constructs an empty Context object.

Returns:

Context

context_from_path(path, previous_context=None)[source]

Factory method that constructs a context object from a path on disk.

Note

If you’re running this method on a render farm or on a machine where the path cache may not have already been generated then you will need to run synchronize_filesystem_structure() beforehand, otherwise you will get back a context only containing the shotgun site URL.

Parameters:
  • path – a file system path

  • previous_context (Context) – A context object to use to try to automatically extend the generated context if it is incomplete when extracted from the path. For example, the Task may be carried across from the previous context if it is suitable and if the task wasn’t already expressed in the file system path passed in via the path argument.

Returns:

Context

context_from_entity(entity_type, entity_id)[source]

Factory method that constructs a context object from a Shotgun entity.

Parameters:
  • entity_type – The name of the entity type.

  • entity_id – Shotgun id of the entity upon which to base the context.

Returns:

Context

context_from_entity_dictionary(entity_dictionary)[source]

Derives a context from a shotgun entity dictionary. This will try to use any linked information available in the dictionary where possible but if it can’t determine a valid context then it will fall back to context_from_entity() which may result in a Shotgun path cache query and be considerably slower.

The following values for entity_dictionary will result in a context being created without falling back to a potential Shotgun query - each entity in the dictionary (including linked entities) must have the fields: ‘type’, ‘id’ and ‘name’ (or the name equivalent for specific entity types, e.g. ‘content’ for Step entities, ‘code’ for Shot entities, etc.):

{"type": "Project", "id": 123, "name": "My Project"}

{"type": "Shot", "id": 456, "code": "Shot 001",
 "project": {"type": "Project", "id": 123, "name": "My Project"}
}

{"type": "Task", "id": 789, "content": "Animation",
 "project": {"type": "Project", "id": 123, "name": "My Project"}
 "entity": {"type": "Shot", "id": 456, "name": "Shot 001"}
 "step": {"type": "Step", "id": 101112, "name": "Anm"}
}

{"type": "PublishedFile", "id": 42, "code": "asset.ma",
 "task": {type": "Task", "id": 789, "content": "Animation"}
 "project": {"type": "Project", "id": 123, "name": "My Project"}
 "entity": {"type": "Shot", "id": 456, "name": "Shot 001"}
}

The following values for entity_dictionary don’t contain enough information to fully form a context so the code will fall back to context_from_entity() which may then result in a Shotgun query to retrieve the missing information:

# missing project name
{"type": "Project", "id": 123}

# missing linked project
{"type": "Shot", "id": 456, "code": "Shot 001"}

# missing linked project name and linked step
{"type": "Task", "id": 789, "content": "Animation",
 "project": {"type": "Project", "id": 123}}
 "entity": {"type": "Shot", "id": 456, "name": "Shot 001"}
}

# Missing publish name.
{"type": "PublishedFile", "id": 42,
 "task": {type": "Task", "id": 789, "content": "Animation"}
 "project": {"type": "Project", "id": 123, "name": "My Project"}
 "entity": {"type": "Shot", "id": 456, "name": "Shot 001"}
}
Parameters:

entity_dictionary – A Shotgun entity dictionary containing at least ‘type’ and ‘id’. See examples above.

Returns:

Context

synchronize_filesystem_structure(full_sync=False)[source]

Ensures that the filesystem structure on this machine is in sync with Shotgun. This synchronization is implicitly carried out as part of the normal folder creation process, however sometimes it is useful to be able to call it on its own.

Note

That this method is equivalent to the synchronize_folders tank command.

Parameters:

full_sync – If set to true, a complete sync will be carried out. By default, the sync is incremental.

Returns:

List of folders that were synchronized.

create_filesystem_structure(entity_type, entity_id, engine=None)[source]

Create folders and associated data on disk to reflect branches in the project tree related to a specific entity.

It is possible to set up folder creation so that it happens in two passes - a primary pass and a deferred pass. Typically, the primary pass is used to create the high level folder structure and the deferred is executed just before launching an application environment. It can be used to create application specific folders or to create a user workspace based on the user launching the application. By setting the optional engine parameter to a string value (typically the engine name, for example tk-maya) you can indicate to the system that it should trigger the deferred pass and recurse down in the part of the configuration that has been marked as being deferred in the configuration.

Note that this is just a string following a convention - typically, we recommend that an engine name (e.g. ‘tk-nuke’) is passed in, however all this method is doing is to relay this string on to the folder creation (schema) setup so that it is compared with any deferred entries there. In case of a match, the folder creation will recurse down into the subtree marked as deferred.

Parameters:
  • entity_type – Shotgun entity type

  • entity_id – Shotgun id

  • engine – Optional engine name to indicate that a second, engine specific folder creation pass should be executed for a particular engine.

Returns:

The number of folders processed

preview_filesystem_structure(entity_type, entity_id, engine=None)[source]

Previews folders that would be created by create_filesystem_structure().

Parameters:
  • entity_type – Shotgun entity type

  • entity_id – Shotgun id

  • engine (String.) – Optional engine name to indicate that a second, engine specific folder creation pass should be executed for a particular engine.

Returns:

List of paths that would be created

Authentication

Certain API operations require Flow Production Tracking data and hence require a way for the API to establish a connection to Flow Production Tracking. The easiest way to handle this is by making sure that each API instance has an associated authenticated user:

sgtk.set_authenticated_user(user)[source]

Sets the currently authenticated Shotgun user for the current toolkit session.

You instruct the Toolkit API which user the current session is associated with by executing this command. Conversely, you can use get_authenticated_user() to retrieve the current user. The user object above is created by the sgtk.authentication part of the API and wraps around the Shotgun API to provide a continuous and configurable experience around user based Shotgun connections.

Normally, Toolkit handles this transparently as part of setting up the sgtk instance and there is no need to call this method. However, if you are running a custom tool which has particular requirements around authentication, you can provide your own logic if desirable.

Parameters:

user – A ShotgunUser derived object. Can be None to clear the authenticated user.

sgtk.get_authenticated_user()[source]

Returns the Shotgun user associated with Toolkit.

Returns:

A ShotgunUser derived object if set, None otherwise.

Note

The Context serializes the authentication state, so if you are passing a context from one process or application to the next, you don’t need to utilize the methods above.

Pipeline Configuration Utilities

It is possible to enquiry about the location of various components of the pipeline configuration and the currently running version of the Toolkit Core.

sgtk.get_core_python_path_for_config(pipeline_config_path)[source]

Returns the location of the Toolkit library associated with the given pipeline configuration.

Parameters:

pipeline_config_path – path to a pipeline configuration

Returns:

Path to location where the Toolkit Python library associated with the config resides.

Return type:

str

sgtk.get_sgtk_module_path()[source]

Returns the path to sgtk module. This path can be used by another process to update its PYTHONPATH and use the same sgtk module as the process invoking this method.

For example, if the Toolkit core was installed at /home/user/.shotgun/bundle_cache/app_store/tk-core/v0.18.94, the method would return /home/user/.shotgun/bundle_cache/app_store/tk-core/v0.18.94/python.

Note

This method can be invoked for cores that are part of a pipeline configuration, that lives inside the bundle cache or a development copy of the core.

Returns:

Path to the sgtk module on disk.

sgtk.get_python_interpreter_for_config(pipeline_config_path)[source]

Retrieves the path to the Python interpreter for a given pipeline configuration path.

Each pipeline configuration has three (one for Windows, one for macOS and one for Linux) interpreter files that provide a path to the Python interpreter used to launch the tank command.

If you require a python executable to launch a script that will use a pipeline configuration, it is recommended its associated Python interpreter.

Deprecated since version v0.18.94: You can now access the content of the interpreter_*.yml through the ConfigDescriptor.python_interpreter() property.

>>> engine = sgtk.platform.current_engine()
>>> descriptor = engine.sgtk.configuration_descriptor
>>> print descriptor.python_interpreter
Parameters:

pipeline_config_path (str) – Path to the pipeline configuration root.

Returns:

Path to the Python interpreter for that configuration.

Return type:

str

Raises:

Context

class sgtk.Context(tk, project=None, entity=None, step=None, task=None, user=None, additional_entities=None, source_entity=None)[source]

A context instance is used to collect a set of key fields describing the current Context. We sometimes refer to the context as the current work area. Typically this would be the current shot or asset that someone is working on.

The context captures the current point in both shotgun and the file system and context objects are launch a toolkit engine via the sgtk.platform.start_engine() method. The context points the engine to a particular point in shotgun and on disk - it could be something as detailed as a task inside a Shot, and something as vague as an empty context.

The context is split up into several levels of granularity, reflecting the fundamental hierarchy of Shotgun itself.

  • The project level defines which shotgun project the context reflects.

  • The entity level defines which entity the context reflects. For example, this may be a Shot or an Asset. Note that in the case of a Shot, the context does not contain any direct information of which sequence the shot is linked to, however the context can still resolve such relationships implicitly if needed - typically via the Context.as_context_fields() method.

  • The step level defines the current pipeline step. This is often a reflection of a department or a general step in a workflow or pipeline (e.g. Modeling, Rigging).

  • The task level defines a current Shotgun task.

  • The user level defines the current user.

The data forms a hierarchy, so implicitly, the task belongs to the entity which in turn belongs to the project. The exception to this is the user, which simply reflects the currently operating user.

Context objects are not constructed by hand but are fabricated by the methods Sgtk.context_from_entity(), Sgtk.context_from_entity_dictionary() and Sgtk.context_from_path().

property project

The shotgun project associated with this context.

If the context is incomplete, it is possible that the property is None. Example:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_path("/studio.08/demo_project/sequences/AAA/ABC/Light/work")
>>> ctx.project
{'type': 'Project', 'id': 4, 'name': 'demo_project'}
Returns:

A std shotgun link dictionary with keys id, type and name, or None if not defined

property entity

The shotgun entity associated with this context.

If the context is incomplete, it is possible that the property is None. Example:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_path("/studio.08/demo_project/sequences/AAA/ABC/Light/work")
>>> ctx.entity
{'type': 'Shot', 'id': 412, 'name': 'ABC'}
Returns:

A std shotgun link dictionary with keys id, type and name, or None if not defined

property source_entity

The Shotgun entity that was used to construct this Context.

This is not necessarily the same as the context’s “entity”, as there are situations where a context is interpreted from an input entity, such as when a PublishedFile entity is used to determine a context. In that case, the original PublishedFile becomes the source_entity, and project, entity, task, and step are determined by what the PublishedFile entity is linked to. A specific example of where this is useful is in a pick_environment core hook. In that hook, an environment is determined based on a provided Context object. In the case where we want to provide a specific environment for a Context built from a PublishedFile entity, the context’s source_entity can be used to know for certain that it was constructured from a PublishedFile.

Returns:

A Shotgun entity dictionary.

Return type:

dict or None

property step

The shotgun step associated with this context.

If the context is incomplete, it is possible that the property is None. Example:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_path("/studio.08/demo_project/sequences/AAA/ABC/Light/work")
>>> ctx.step
{'type': 'Step', 'id': 12, 'name': 'Light'}
Returns:

A std shotgun link dictionary with keys id, type and name, or None if not defined

property task

The shotgun task associated with this context.

If the context is incomplete, it is possible that the property is None. Example:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_path("/studio.08/demo_project/sequences/AAA/ABC/Lighting/first_pass_lgt/work")
>>> ctx.task
{'type': 'Task', 'id': 212, 'name': 'first_pass_lgt'}
Returns:

A std shotgun link dictionary with keys id, type and name, or None if not defined

property user

A property which holds the user associated with this context. If the context is incomplete, it is possible that the property is None.

The user property is special - either it represents a user value that was baked into a template path upon folder creation, or it represents the current user:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_path("/studio.08/demo_project/sequences/AAA/ABC/Lighting/dirk.gently/work")
>>> ctx.user
{'type': 'HumanUser', 'id': 23, 'name': 'Dirk Gently'}
Returns:

A std shotgun link dictionary with keys id, type and name, or None if not defined

property additional_entities

List of entities that are required to provide a full context in non-standard configurations. The “context_additional_entities” core hook gives the context construction code hints about how this data should be populated.

Warning

This is an old and advanced option and may be deprecated in the future. We strongly recommend not using it.

Returns:

A list of std shotgun link dictionaries. Will be an empty list in most cases.

property entity_locations

A list of paths on disk which correspond to the entity which this context represents. If no folders have been created for this context yet, the value of this property will be an empty list:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_entity("Task", 8)
>>> ctx.entity_locations
['/studio.08/demo_project/sequences/AAA/ABC']
Returns:

A list of paths

property shotgun_url

Returns the shotgun detail page url that best represents this context. Depending on the context, this may be a task, a shot, an asset or a project. If the context is completely empty, the root url of the associated shotgun installation is returned.

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_entity("Task", 8)
>>> ctx.shotgun_url
'https://mystudio.shotgunstudio.com/detail/Task/8'
property filesystem_locations

A property which holds a list of paths on disk which correspond to this context. If no folders have been created for this context yet, the value of this property will be an empty list:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_entity("Task", 8)
>>> ctx.filesystem_locations
['/studio.08/demo_project/sequences/AAA/ABC/light/initial_pass']
Returns:

A list of paths

property sgtk

The Toolkit API instance associated with this context

Returns:

Sgtk

as_template_fields(template, validate=False)[source]

Returns the context object as a dictionary of template fields.

This is useful if you want to use a Context object as part of a call to the Sgtk API. In order for the system to pass suitable values, you need to pass the template you intend to use the data with as a parameter to this method. The values are derived from existing paths on disk, or in the case of keys with shotgun_entity_type and shotgun_entity_field settings, direct queries to the Shotgun server. The validate parameter can be used to ensure that the method returns all context fields required by the template and if it can’t then a TankError will be raised. Example:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")

# Create a template based on a path on disk. Because this path has been
# generated through Toolkit's folder processing and there are corresponding
# FilesystemLocation entities stored in Shotgun, the context can resolve
# the path into a set of Shotgun entities.
#
# Note how the context object, once resolved, does not contain
# any information about the sequence associated with the Shot.
>>> ctx = tk.context_from_path("/studio.08/demo_project/sequences/AAA/ABC/Lighting/work")
>>> ctx.project
{'type': 'Project', 'id': 4, 'name': 'demo_project'}
>>> ctx.entity
{'type': 'Shot', 'id': 2, 'name': 'ABC'}
>>> ctx.step
{'type': 'Step', 'id': 1, 'name': 'Light'}

# now if we have a template object that we want to turn into a path,
# we can request that the context object attempts to resolve as many
# fields as it can. These fields can then be plugged into the template
# object to generate a path on disk
>>> templ = tk.templates["maya_shot_publish"]
>>> templ
<Sgtk TemplatePath maya_shot_publish: sequences/{Sequence}/{Shot}/{Step}/publish/{name}.v{version}.ma>

>>> fields = ctx.as_template_fields(templ)
>>> fields
{'Step': 'Lighting', 'Shot': 'ABC', 'Sequence': 'AAA'}

# the fields dictionary above contains all the 'high level' data that is necessary to realise
# the template path. An app or integration can now go ahead and populate the fields specific
# for the app's business logic - in this case name and version - and resolve the fields dictionary
# data into a path.
Parameters:
  • templateTemplate for which the fields will be used.

  • validate – If True then the fields found will be checked to ensure that all expected fields for the context were found. If a field is missing then a TankError will be raised

Returns:

A dictionary of template files representing the context. Handy to pass to for example Template.apply_fields().

Raises:

TankError if the fields can’t be resolved for some reason or if ‘validate’ is True and any of the context fields for the template weren’t found.

create_copy_for_user(user)[source]

Provides the ability to create a copy of an existing Context for a specific user.

This is useful if you need to determine a user specific version of a path, e.g. when copying files between different user sandboxes. Example:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_path("/studio.08/demo_project/sequences/AAA/ABC/Lighting/dirk.gently/work")
>>> ctx.user
{'type': 'HumanUser', 'id': 23, 'name': 'Dirk Gently'}
>>>
>>> copied_ctx = tk.create_copy_for_user({'type': 'HumanUser', 'id': 7, 'name': 'John Snow'})
>>> copied_ctx.user
{'type': 'HumanUser', 'id': 23, 'name': 'John Snow'}
Parameters:

user – The Shotgun user entity dictionary that should be set on the copied context

Returns:

Context

serialize(with_user_credentials=True, use_json=False)[source]

Serializes the context into a string.

Any Context object can be serialized to/deserialized from a string. This can be useful if you need to pass a Context between different processes. As an example, the tk-multi-launchapp uses this mechanism to pass the Context from the launch process (e.g. for example PTR desktop app) to the Application (e.g. Maya) being launched. Example:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")
>>> ctx = tk.context_from_path("/studio.08/demo_project/sequences/AAA/ABC/Lighting/dirk.gently/work")
>>> context_str = ctx.serialize(ctx)
>>> new_ctx = sgtk.Context.deserialize(context_str)
Parameters:
  • with_user_credentials – If True, the currently authenticated user’s credentials, as returned by sgtk.get_authenticated_user(), will also be serialized with the context.

  • use_json – If True, the context will be stored in the JSON representation instead of using the pickled representation.

Note

For example, credentials should be omitted (with_user_credentials=False) when serializing the context from a user’s current session to send it to a render farm. By doing so, invoking sgtk.Context.deserialize() on the render farm will only restore the context and not the authenticated user.

Returns:

String representation

classmethod deserialize(context_str)[source]

The inverse of Context.serialize().

Parameters:

context_str – String representation of context, created with Context.serialize()

Note

If the context was serialized with the user credentials, the currently authenticated user will be updated with these credentials.

Returns:

Context

to_dict()[source]

Converts the context into a dictionary with keys project, entity, user, step, task, additional_entities and source_entity.

Note

Contrary to Context.serialize(), this method discards information about the Toolkit instance associated with the context or the currently authenticated user.

Returns:

A dictionary representing the context.

classmethod from_dict(tk, data)[source]

Converts a dictionary into a Context object.

You should only pass in a dictionary that was created with the Context.to_dict() method.

Parameters:
  • data (dict) – A dictionary generated from Context.to_dict().

  • tk (Sgtk) – Toolkit instance to associate with the context.

Returns:

A newly created Context object.

Commands

The tank command offers a variety of system utility commands to handle for example upgrades, administration and maintenance. These commands are also available to use via the API in order to make it easy to integrate Toolkit maintenance workflows with other scriped workflows you may have in your studio. The following commands can be used to manage and execute these functions:

API access methods

sgtk.list_commands(tk=None)[source]

Lists the system commands registered with the system.

If you leave the optional tk parameter as None, a list of global commands will be returned. These commands can be executed at any point and do not require a project or a configuration to be present. Examples of such commands are the core upgrade check and the setup_project commands:

>>> import sgtk
>>> sgtk.list_commands()
['setup_project', 'core']

If you do pass in a tk API handle (or alternatively use the convenience method Sgtk.list_commands()), all commands which are available in the context of a project configuration will be returned. This includes for example commands for configuration management, anything app or engine related and validation and overview functionality. In addition to these commands, the global commands will also be returned:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> tk.list_commands()
['setup_project', 'core', 'localize', 'validate', 'cache_apps', 'clear_cache',
 'app_info', 'install_app', 'install_engine', 'updates', 'configurations', 'clone_configuration']
Parameters:

tk (Sgtk) – Optional Toolkit API instance

Returns:

list of command names

sgtk.get_command(command_name, tk=None)[source]

Returns an instance of a command object that can be used to execute a command.

Once you have retrieved the command instance, you can perform introspection to check for example the required parameters for the command, name, description etc. Lastly, you can execute the command by running the execute() method.

In order to get a list of the available commands, use the list_commands() method.

Certain commands require a project configuration context in order to operate. This needs to be passed on in the form of a toolkit API instance via the tk parameter. See the list_command() documentation for more details.

Parameters:
  • command_name – Name of command to execute. Get a list of all available commands using the list_commands() method.

  • tk (Sgtk) – Optional Toolkit API instance

Returns:

SgtkSystemCommand

SgtkSystemCommand

class sgtk.SgtkSystemCommand(internal_action_object, tk)[source]

Represents a toolkit system command.

You can use this object to introspect command properties such as name, description, parameters etc. Execution is carried out by calling the execute() method.

For a global command which doesn’t require an active configuration, execution typically looks like this:

>>> import sgtk

>>> sgtk.list_commands()
['setup_project', 'core']

>>> cmd = sgtk.get_command("core")
>>> cmd
<tank.deploy.tank_command.SgtkSystemCommand object at 0x106d9f090>

>>> cmd.execute({})

Instances should be constructed using the get_command() factory method.

property parameters

The different parameters that needs to be specified and if a parameter has any default values. For example:

{ "parameter_name": { "description": "Parameter info",
                    "default": None,
                    "type": "str" },

 ...

 "return_value": { "description": "Return value (optional)",
                   "type": "str" }
}
property description

A brief description of this command.

property name

The name of this command.

property category

The category for this command. This is typically a short string like “Admin”.

property logger

The python Logger associated with this tank command

set_logger(log)[source]

Specify a standard python log instance to send logging output to. If this is not specify, the standard output mechanism will be used.

Warning

We strongly recommend using the logger() property to retrieve the default logger for the tank command and attaching a handler to this rather than passing in an explicit log object via this method. This method may be deprecated at some point in the future.

Parameters:

log – Standard python logging instance

execute(params, interaction_interface=None)[source]

Execute this command.

Parameters:
  • params – dictionary of parameters to pass to this command. the dictionary key is the name of the parameter and the value is the value you want to pass. You can query which parameters can be passed in via the parameters property.

  • interaction_interface – Optional interaction interface. This will be used whenever the command needs to interact with the user. Should be an instance deriving from CommandInteraction.

Returns:

Whatever the command returns. Data type and description for the return value can be introspected via the parameters() property.

terminate()[source]

Instructs the command to attempt to terminate its execution. Not all commands are able to terminate and execution normally does not terminate straight away.

CommandInteraction

class sgtk.CommandInteraction[source]

Base class interface for tank command interaction. This can be subclassed in order to provide a custom interaction environment when running commands in API mode.

In order to override the built-in interaction behavior, pass an instance of a command interaction class to the sgtk.SgtkSystemCommand.execute() method.

property supports_interaction

True if interaction is supported, false if not. Implementations returning False here typically implement other methods by returning default values without prompting the user for feedback.

request_input(message)[source]

Request general input from the user.

Parameters:

message (str) – Message to display

Returns:

Information entered by user.

Return type:

str

ask_yn_question(message)[source]

Prompts the user with a yes/no question.

Parameters:

message (str) – Message to display

Returns:

True if user selects yes, false if no.

ask_yna_question(message, force_prompt=False)[source]

Prompts the user with a yes/no/always question.

Always means that further calls to this method will return True.

Parameters:
  • message (str) – Message to display

  • force_prompt (bool) – Force a prompt, even if always has been selected in the past.

Returns:

True if user selects yes, false if no.

Hooks

Hooks are snippets of code that can be customized as part of the configuration of a Toolkit app, engine or core itself. You can use hooks with the Core API (we call those core hooks) and with apps and engines. Hooks are a central concept in the configuration of Toolkit. We use hooks whenever there is a need to expose code and allow it to be customized. Examples of when this is useful is Disk I/O, launching of applications, DCC-specific logic and permissions control.

Hook

class sgtk.Hook(parent)[source]

Hooks are implemented in a python file and they all derive from a Hook base class.

If you are writing an app that loads files into Maya, Nuke or other DCCs, a hook is a good way to expose the actual loading logic, so that not only can be customized by a user, but so that you could even add support for a new DCC to your load app without having to update it.

First, you would create a hooks/actions.py file in your app. This would contain a hook class:

import sgtk
HookBaseClass = sgtk.get_hook_baseclass()

class Actions(HookBaseClass):

    def list_actions(self, sg_publish_data):
        '''
        Given some Shotgun publish data, return a list of
        actions that can be performed

        :param sg_publish_data: Dictionary of publish data from Shotgun
        :returns: List of action strings
        '''
        # The base implementation implements an action to show
        # the item in Shotgun
        return ["show_in_sg"]

    def run_action(self, action, sg_publish_data):
        '''
        Execute the given action

        :param action: name of action. One of the items returned by list_actions.
        :param sg_publish_data: Dictionary of publish data from Shotgun
        '''
        if action == "show_in_sg":

            url = "%s/detail/%s/%d" % (
                self.parent.shotgun.base_url,
                sg_publish_data["type"],
                sg_publish_data["id"]
                )
            QtGui.QDesktopServices.openUrl(QtCore.QUrl(url))

The above code forms a generic base for your hook with a basic implementation that works everywhere.

In the app manifest (info.yml), where we define all the basic configuration properties for the app, we define an actions hook:

configuration:

    actions_hook:
        type: hook
        default_value: "{self}/actions.py"
        description: Hook which contains all methods for action management.

From the app code itself, you can now use execute_hook_method() to call out to the hook:

# when creating a list of items in the UI for your app -
# given a shotgun publish, build a menu of avaialable actions:
actions = self.execute_hook_method("actions_hook", "list_actions", sg_data)

# in a callback method once a user has selected an action -
# call out to the hook to execute the action
self.execute_hook_method("actions_hook", "run_action", action_name, sg_data)

In the configuration for your app, you can now ‘glue together’ different functionality for different scenarios. For example, when you install the app to run inside the Maya engine, you want to be able to import maya files into maya. We implement this by adding a custom publish hook for maya. This can either be placed with the app itself, in the hooks folder in the configuration, or in the maya engine. In this case, we’ll add a hooks/actions.py to the maya engine. This file looks like this:

import sgtk
HookBaseClass = sgtk.get_hook_baseclass()

class MayaActions(HookBaseClass):

    def list_actions(self, sg_publish_data):
        '''
        Given some Shotgun publish data, return a list of
        actions that can be performed

        :param sg_publish_data: Dictionary of publish data from Shotgun
        :returns: List of action strings
        '''
        # first get base class actions
        actions = HookBaseClass.list_actions(sg_publish_data)

        # Add maya actions
        if sg_publish_data["published_file_type"]["name"] == "Maya Scene":
            actions += ["reference", "import"]

    def run_action(self, action, sg_publish_data):
        '''
        Execute the given action

        :param action: name of action. One of the items returned by list_actions.
        :param sg_publish_data: Dictionary of publish data from Shotgun
        '''
        if action == "reference":
            # do maya reference operation

        elif action == "import":
            # do maya import operation

        else:
            # pass on to base class
            return HookBaseClass.run_action(action, sg_publish_data)

The above hook implements a couple of actions that are designed to work in Maya. Lastly, we need to tell the app to pick up this file. In the environment configuration for the app running inside of maya, we point it at our engine specific hook:

tk-maya:
    tk-multi-myapp:
        actions_hook: '{engine}/actions.py'

When we are running the app configuration in maya, the actions hook will automatically resolve the hook code distributed with the maya engine. The base class will be automatically determined to be the default value set in the manifest, allowing for the app to carry a default base implementation that is always taken into account.

Resolving paths to hooks

Several different path formats exist, making this a very powerful configuration mechanism:

  • {self}/path/to/foo.py – looks in the hooks folder in the local app, engine of framework.

  • {self}/{engine_name}_publish.py – If running in maya, looks for a tk-maya_publish.py in the hooks folder in the local app, engine of framework. If running in Nuke, it would instead look for BUNDLE_ROOT/hooks/tk-nuke_publish.py.

  • {config}/path/to/foo.py – Looks in the hooks folder in the configuration.

  • {$HOOK_PATH}/path/to/foo.py – expression based around an environment variable.

  • {engine}/path/to/foo.py – looks in the hooks folder of the current engine.

  • {tk-framework-perforce_v1.x.x}/path/to/foo.py – looks in the hooks folder of a framework instance that exists in the current environment. Basically, each entry inside the frameworks section in the current environment can be specified here - all these entries are on the form frameworkname_versionpattern, for example tk-framework-widget_v0.1.2 or tk-framework-shotgunutils_v1.3.x.

Supported legacy formats:

  • foo – Equivalent to {config}/foo.py

You can also provide your own inheritance chains. For example, if you wanted to add your own, project specific maya hooks to this app, you could do this by creating a hook file, placing it in your configuration’s hooks folder and then configure it like this:

tk-maya:
    tk-multi-myapp:
        actions_hook: '{engine}/actions.py:{config}/maya_actions.py'

This would execute your maya_actions.py hook and make sure that that hook inherits from the engine specific hook, making sure that you get both your custom actions, the engine default actions and the app’s built-in actions.

property sgtk

The sgtk core API instance associated with the Hook parent.

This is a convenience method for easy core API instance access. In the case of app, engine and framework hooks, this is equivalent to parent.sgtk and in the case of core hooks it simply returns parent.

Note

Some low level hooks do not have a parent defined. In such cases, None is returned.

property tank

The sgtk core API instance associated with the Hook parent.

Deprecated since version v0.18.70: Use sgtk() instead.

property parent

The parent object to the executing hook. This varies with the type of hook that is being executed. For a hook that runs inside an app or an engine, the parent object will be the Application or Engine instance. For core hooks, the parent object will be sgtk.

Note

If you need to access Shotgun inside your hook, you can do this by calling self.parent.shotgun since both Apps, Engines and the Core API has a shotgun property.

get_publish_path(sg_publish_data)[source]

Returns the path on disk for a publish entity in Shotgun.

Convenience method that calls sgtk.util.resolve_publish_path().

Parameters:

sg_publish_data – Dictionaries containing Shotgun publish data. Each dictionary needs to at least contain a code, type, id and a path key.

Returns:

A path on disk to existing file or file sequence.

Raises:

PublishPathNotDefinedError if the path isn’t defined.

Raises:

PublishPathNotSupported if the path cannot be resolved.

property disk_location

The folder on disk where this item is located. This can be useful if you want to write hook code to retrieve a local resource:

hook_icon = os.path.join(self.disk_location, "icon.png")
property logger

Standard python Logger handle for this hook.

The logger can be used to report progress back to the app in a standardized fashion and will be parented under the app/engine/framework logger:

# pattern
sgtk.env.environment_name.engine_name.app_name.hook.hook_file_name

# for example
sgtk.env.asset.tk-maya.tk-multi-loader2.hook.filter_publishes

In the case of core hooks, the logger will be parented under sgtk.core.hook. For more information, see Logging

load_framework(framework_instance_name)[source]

Loads and returns a framework given an environment instance name.

Note

This method only works for hooks that are executed from apps and frameworks.

If you have complex logic and functionality and want to manage (and version it) as part of a framework rather than in a hook, you can do this by calling a configured framework from inside a hook:

import sgtk
HookBaseClass = sgtk.get_hook_baseclass()

class SomeHook(HookBaseClass):

    def some_method(self):

        # first get a framework handle. This object is similar to an app or engine object
        fw = self.load_framework("tk-framework-library_v1.x.x")

        # now just like with an app or an engine, if you want to access code in the python
        # folder, you can do import_plugin
        module = fw.import_module("some_module")

        module.do_stuff()

Note how we are accessing the framework instance tk-framework-library_v1.x.x above. This needs to be defined in the currently running environment, as part of the frameworks section:

engines:
  # all engine and app defs here...

frameworks:
 # define the framework that we are using in the hook
 tk-framework-library_v1.x.x:
    location: {type: git, path: 'https://github.com/foo/tk-framework-library.git', version: v1.2.6}
Parameters:

framework_instance_name – Name of the framework instance to load from the environment.

get_hook_baseclass

sgtk.get_hook_baseclass()

Returns the base class to use for the hook currently being loaded. For more details and examples, see the Hook documentation.

Core Hooks

The Toolkit core comes with a set of hooks that can help you tweak how the core behaves. If you want to take over a certain behavior, copy the hook found inside the core’s hooks folder and copy it to your configuration’s core/hooks folder.

Note

A core hook cannot be executed before Toolkit (the Sgtk instance) has been initialized. This happens when ToolkitManager.bootstrap_engine() is called during Flow Production Tracking bootstrap. Any customization of the core behavior must be added afterwards.

Here is the list of hooks that be taken over in the Toolkit core.

before_register_publish.py

Hook that gets executed before a publish record is created in Shotgun. This hook makes it possible to add custom fields to a publish before it gets created as well as modifying the content that is being pushed to Shotgun.

class before_register_publish.BeforeRegisterPublish(parent)[source]
execute(shotgun_data, context, **kwargs)[source]

Executed just before a new publish entity is created in Shotgun.

The default implementation returns shotgun_data untouched.

Parameters:
  • shotgun_data (dict) – All the data which will be passed to the Shotgun create call

  • context (Context) – The context of the publish

Returns:

return (potentially) modified data dictionary

Return type:

dict

bootstrap.py

This hook is used override some of the functionality of the ToolkitManager.

It will be instantiated only after a configuration has been selected by the ToolkitManager. Therefore, this hook will not be invoked to download a configuration. However, the Toolkit Core, applications, frameworks and engines can be downloaded through the hook.

class bootstrap.Bootstrap(parent)[source]
init(shotgun, pipeline_configuration_id, configuration_descriptor, **kwargs)[source]

Initializes the hook.

This method is called right after the bootstrap manager reads this hook and passes in information about the pipeline configuration that will be used.

The default implementation copies the arguments into the attributes named shotgun, pipeline_configuration_id and configuration_descriptor.

Parameters:
  • shotgun (Shotgun) – Connection to the Shotgun site.

  • pipeline_configuration_id (int) – Id of the pipeline configuration we’re bootstrapping into. If None, the ToolkitManager is bootstrapping into the base configuration.

  • configuration_descriptor (ConfigDescriptor) – Configuration the manager is bootstrapping into.

can_cache_bundle(descriptor)[source]

Indicates if a bundle can be cached by the populate_bundle_cache_entry() method.

This method is invoked when the bootstrap manager wants to a bundle used by a configuration.

The default implementation returns False.

Parameters:

descriptor – Descriptor of the bundle that needs to be cached.

Returns:

True if the bundle cache be cached with this hook, False if not.

Return type:

bool

populate_bundle_cache_entry(destination, descriptor, **kwargs)[source]

Populates an entry from the bundle cache.

This method will be invoked for every bundle for which can_cache_bundle() returned True. The hook is responsible for writing the bundle inside the destination folder. If an exception is raised by this method, the files will be deleted from disk and the bundle cache will be left intact.

Be careful to properly copy all the files or the cache for this bundle will be left in an inconsistent state.

The default implementation does nothing.

Parameters:
  • destination (str) – Folder where the bundle needs to be written. Note that this is not the final destination folder inside the bundle cache.

  • descriptor – Descriptor of the bundle that needs to be cached.

bundle_init.py

Hook that gets executed every time a bundle is fully initialized.

class bundle_init.BundleInit(parent)[source]
execute(bundle, **kwargs)[source]

Executed when the Toolkit bundle is fully initialized.

The default implementation does nothing.

Parameters:

bundle (Engine, Framework or Application) – The Toolkit bundle that has been initialized.

cache_location.py

Hook to control path cache and bundle cache folder creation.

class cache_location.CacheLocation(parent)[source]
get_path_cache_path(project_id, plugin_id, pipeline_configuration_id)[source]

Establish a location for the path cache database file.

This hook method was introduced in Toolkit v0.18 and replaces the previous path_cache method. If you already have implemented path_cache, this will be detected and called instead, however we strongly recommend that you tweak your hook.

Overriding this method in a hook allows a user to change the location on disk where the path cache file is located. The path cache file holds a temporary cache representation of the FilesystemLocation entities stored in Shotgun for a project.

The default implementation will create a folder inside the user’s home folder or under SHOTGUN_HOME.

Parameters:
  • project_id (int) – The Shotgun id of the project to store caches for. None if the configuration is a site configuration.

  • plugin_id (str) – Unique string to identify the scope for a particular plugin or integration. For more information, see plugin_id(). For non-plugin based toolkit projects, this value is None.

  • pipeline_configuration_id (int) – The Shotgun pipeline configuration id to store caches for. If the pipeline configuration is unmanaged, it will be None

Returns:

The path to a path cache file. This file should exist when this method returns.

Return type:

str

get_bundle_data_cache_path(project_id, plugin_id, pipeline_configuration_id, bundle)[source]

Establish a cache folder for an app, engine or framework.

This hook method was introduced in Toolkit v0.18 and replaces the previous bundle_cache method. If you already have implemented bundle_cache, this will be detected and called instead, however we strongly recommend that you tweak your hook.

Apps, Engines or Frameworks commonly cache data on disk. This can be small files, Shotgun queries, thumbnails, etc. This method implements the logic which defines this location on disk. The cache should be organized in a way so that all instances of the app can re-use the same data. Bundles which need to cache things per-instance can implement this using a sub folder inside the bundle cache location.

It is possible to omit some components of the path by explicitly passing a None value for them. Only the bundle name is required. For example, with project_id=None, a site level cache path will be returned. Omitting the project_id can be used to cache data for the site configuration, or to share data accross all projects belonging to a common site.

The default implementation will create a folder inside the user’s home folder or under SHOTGUN_HOME.

Parameters:
  • project_id (int) – The Shotgun id of the project to store caches for, or None.

  • plugin_id (str) – Unique string to identify the scope for a particular plugin or integration, or None. For more information, see plugin_id(). For non-plugin based toolkit projects, this value is None.

  • pipeline_configuration_id (int) – The Shotgun pipeline config id to store caches for or None if the pipeline configuration is unmanaged.

  • bundle (Engine, Framework or Application) – The app, engine or framework object which is requesting the cache folder.

Returns:

The path to a folder which should exist on disk.

Return type:

str

context_change.py

This hook gets executed before and after the context changes in Toolkit.

class context_change.ContextChange(parent)[source]
  • If an engine starts up, the current_context passed to the hook methods will be None and the next_context parameter will be set to the context that the engine is starting in.

  • If an engine is being reloaded, in the context of an engine restart for example, the current_context and next_context will usually be the same.

  • If a context switch is requested, for example when a user switches from project to shot mode in Nuke Studio, current_context and next_context will contain two different context.

Note

These hooks are called whenever the context is being set in Toolkit. It is possible that the new context will be the same as the old context. If you want to trigger some behavior only when the new one is different from the old one, you’ll need to compare the two arguments using the != operator.

pre_context_change(current_context, next_context)[source]

Executed before the context has changed.

The default implementation does nothing.

Parameters:
  • current_context (Context) – The context of the engine.

  • next_context (Context) – The context the engine is switching to.

post_context_change(previous_context, current_context)[source]

Executed after the context has changed.

The default implementation does nothing.

Parameters:
  • previous_context (Context) – The previous context of the engine.

  • current_context (Context) – The current context of the engine.

default_storage_root.py

Hook that gets executed during Toolkit initialization. This hook makes it possible to modify the default storage root.

class default_storage_root.DefaultStorageRoot(parent)[source]
execute(storage_roots, project_id=None, metadata=None)[source]

Executes right after constructing a pipeline configuration during Toolkit initialization.

You can find example implementations in the tests/core_tests/test_default_storage_root_hook folder which allow you to switch between storages if you have a different storage root per project.

The default implementation does nothing.

Parameters:
  • storage_roots (StorageRoots) – The storage roots for the project.

  • project_id (int) – id of the project toolkit is being initialized in

  • metadata (dict) – Contents of the Project configuration file.

engine_init.py

Hook that gets executed every time an engine has been fully initialized.

class engine_init.EngineInit(parent)[source]
execute(engine, **kwargs)[source]

Executed when a Toolkit engine has been fully initialized.

At this point, all apps and frameworks have been loaded, and the engine is fully operational.

The default implementation does nothing.

Parameters:

engine (Engine) – Engine that has been initialized.

ensure_folder_exists.py

This hook is called when an engine, app or framework’s ensure_folder_exists method is called.

class ensure_folder_exists.EnsureFolderExists(parent)[source]
execute(path, bundle_obj, **kwargs)[source]

Creates folders on disk.

Toolkit bundles call this method when they want to ensure that a leaf-level folder structure exists on disk. In the case where customization is required, the hook is passed the bundle that issued the original request. This should allow for some sophisticated introspection inside the hook.

The default implementation creates these folders with read/write permissions for everyone.

Parameters:
  • path (str) – path to create

  • bundle_object (Engine, Framework or Application) – Object requesting the creation. This is a legacy parameter and we recommend using self.parent instead.

get_current_login.py

Hook that gets executed when the current user is being retrieved.

Please note that this hook will only be called whenever Toolkit doesn’t have an authenticated user present. In releases prior to v0.16, this was the case for all users and projects. However, as of Core v0.16 and above, projects are set up to require users to log in by default, meaning that there already is a well established notion of who the current user is.

Even with such projects, there are environments, e.g. render farms, where a user cannot easily log in, and a Shotgun script user typically is being used for “headless” operation of Toolkit. In these cases, Toolkit doesn’t know which Shotgun user is associated with the operation and this hook will be called.

The return value from this hook will then be compared with the available logins for all users in Shotgun and if a match is found, this is deemed to be the current user.

class get_current_login.GetCurrentLogin(parent)[source]
execute(**kwargs)[source]

Retrieves the login name for the Shotgun user.

This is used by Toolkit to resolve against the login field in the Shotgun users table in order to extract further metadata.

The default implementation will return the OS user’s login name.

Returns:

A name that matches the user’s login field in Shotgun.

Return type:

str

log_metrics.py

Hook that gets executed every time Toolkit logs user metrics.

class log_metrics.LogMetrics(parent)[source]
log_metrics(metrics)[source]

Called when Toolkit logs a list of metrics.

A metric is a dictionary with three items:

  • event_group (str) - Name of the event group.

  • event_name (str) - Name of the event.

  • event_properties (list) - List of properties for the event.

The default implementation does nothing.

Parameters:

metrics (list(dict)) – List of metrics.

Note

This hook will be executed within one or more dedicated metrics logging worker threads and not in the main thread. Overriding this hook may require additional care to avoid issues related to accessing shared resources across multiple threads.

pick_environment.py

Hook which chooses an environment file to use based on the current context. This file is almost always overridden by a configuration.

class pick_environment.PickEnvironment(parent)[source]
execute(context, **kwargs)[source]

Executed when Toolkit needs to pick an environment file.

The default implementation will return shot or asset based on the type of the entity in sgtk.Context.entity. If the type does not match Shot or Asset, None will be returned.

Params context:

The context for which an environment will be picked.

Returns:

Name of the environment to use or None is there was no match.

Return type:

str

pipeline_configuration_init.py

Hook that gets executed every time a new PipelineConfiguration instance is created.

class pipeline_configuration_init.PipelineConfigurationInit(parent)[source]
execute(**kwargs)[source]

Executed when a new PipelineConfiguration instance is initialized.

The default implementation does nothing.

process_folder_creation.py

This hook is invoked during folder creation when sgtk.Sgtk.create_filesystem_structure() is called.

class process_folder_creation.ProcessFolderCreation(parent)[source]
execute(items, preview_mode, **kwargs)[source]

Creates a list of files and folders.

The default implementation creates files and folders recursively using open permissions.

Parameters:

list(dict) – List of actions that needs to take place.

Six different types of actions are supported.

Standard Folder

This represents a standard folder in the file system which is not associated with anything in Shotgun. It contains the following keys:

  • action (str) - folder

  • metadata (dict) - The configuration yaml data for this item

  • path (str) - path on disk to the item

Entity Folder

This represents a folder in the file system which is associated with a Shotgun entity. It contains the following keys:

  • action (str) - entity_folder

  • metadata (dict) - The configuration yaml data for this item

  • path (str) - path on disk to the item

  • entity (dict) - Shotgun entity link with keys type, id and name.

Remote Entity Folder

This is the same as an entity folder, except that it was originally created in another location. A remote folder request means that your local toolkit instance has detected that folders have been created by a different file system setup. It contains the following keys:

  • action (str) - remote_entity_folder

  • metadata (dict) - The configuration yaml data for this item

  • path (str) - path on disk to the item

  • entity (dict) - Shotgun entity link with keys type, id and name.

File Copy

This represents a file copy operation which should be carried out. It contains the following keys:

  • action (str) - copy

  • metadata (dict) - The configuration yaml data associated with the directory level on which this object exists.

  • source_path (str) - location of the file that should be copied

  • target_path (str) - target location to where the file should be copied.

File Creation

This is similar to the file copy, but instead of a source path, a chunk of data is specified. It contains the following keys:

  • action (str) - create_file

  • metadata (dict) - The configuration yaml data associated with the directory level on which this object exists.

  • content (str) – file content

  • target_path (str) – target location to where the file should be copied.

Symbolic Links

This represents a request that a symbolic link is created. Note that symbolic links are not supported in the same way on all operating systems. The default hook therefore does not implement symbolic link support on Windows systems. If you want to add symbolic link support on windows, simply copy this hook to your project configuration and make the necessary modifications.

  • action (str) - symlink

  • metadata (dict) - The raw configuration yaml data associated with symlink yml config file.

  • path (str) - the path to the symbolic link

  • target (str) - the target to which the symbolic link should point

Returns:

List of files and folders that have been created.

Return type:

list(str)

process_folder_name.py

Core hook which handles conversion of Shotgun field data into strings.

This hook can be used to control how folders are named on disk given a field in Shotgun. Should for example spaces be replaced by underscores or periods when folders are created?

This hook can also be used to raise an exception if an invalid naming convention is being used, for example:

if entity_type == "Shot" and str_value.startswith("AA"):
   raise TankError("Shot names cannot start with AA!")
class process_folder_name.ProcessFolderName(parent)[source]
execute(entity_type, entity_id, field_name, value, **kwargs)[source]

Executed when an entity needs to be turned into a string token during folder creation.

The default implementation will turn non-ascii characters into hyphens and replace spaces with underscores.

For example, {"type":"Shot", "id":123, "name":"Pont de Lévis"} would be converted to Pont_de_L-vis.

Parameters:
  • entity_type (str) – The Shotgun entity type for which the value is taken.

  • entity_id (int) – The entity id representing the data.

  • field_name (str) – The Shotgun field associated with the value.

  • value (object) – The actual value in some form, as returned by the Shotgun API.

Returns:

A string representing the entity.

Return type:

str

resolve_publish.py

Hook used to resolve publish records in Shotgun into local form on a machine during a call to sgtk.util.resolve_publish_path().

class resolve_publish.ResolvePublish(parent)[source]
resolve_path(sg_publish_data)[source]

Resolves a Shotgun publish record into a local file on disk.

If this method returns None, it indicates to Toolkit that the default publish resolution logic should be used.

The default implementation of this hook returns None

Parameters:

sg_publish_data (dict) – Dictionary containing Shotgun publish data. Contains at minimum a code, type, id and a path key.

Returns:

Path to the local file or None.

Rtype str:

tank_init.py

Hook that gets executed every time a new Toolkit API instance is created.

class tank_init.TankInit(parent)[source]
execute(**kwargs)[source]

Executed when a new Toolkit API instance is initialized.

You can access the Toolkit API instance through self.parent.

The default implementation does nothing.

Template Hooks

This hook is a simple example to illustrate how template settings in an app can be evaluated at runtime based on complex conditions.

If you have an app which has a template parameter, you would typically use a setting which points to one of your templates. So in the environment config, you would have:

template_snapshot: maya_shot_publish

However if you want more complex behavior, it is possible to specify that a hook should be used to evaluate the setting at runtime rather than just set it. For example:

template_snapshot: "hook:example_template_hook:maya_shot_publish"

This setting would look for a core hook named example_template_hook and execute it. See below for an example implementation and parameter descriptions.

class example_template_hook.ExampleTemplateHook(parent)[source]
execute(setting, bundle_obj, extra_params, **kwargs)[source]

Example pass-through implementation. One option is expected in extra_params and it will be returned.

So the following two things will evaluate to the same thing:

> template_snapshot: maya_shot_publish > template_snapshot: hook:example_template_hook:maya_shot_publish

Parameters:
  • setting – The name of the setting for which we are evaluating In our example above, it would be template_snapshot.

  • bundle_obj – The app, engine or framework object that the setting is associated with.

  • extra_params – List of options passed from the setting. If the settings string is “hook:hook_name:foo:bar”, extra_params would be [‘foo’, ‘bar’]

returns: needs to return the name of a template, as a string.

Templates

The Toolkit template system is used to handle path and string token manipulations.

Since the Flow Production Tracking is file system based, Apps will need to resolve file paths whenever they need to read or write data from disk. Apps are file system structure agnostic - meaning that they don’t know how the file system is organized. The template system handles all this for them.

At the heart of the template system, there is a Templates Configuration File. This file contains all the important file system locations for a project. A Template looks something like this:

maya_shot_publish: 'shots/{Shot}/{Step}/pub/{name}.v{version}.ma'

It basically defines a path which contains certain dynamic fields. Each field can be configured with validation and typing, so you can, for example, define that the {version} field in the template above is an integer padded with three zeros (e.g. 001, 012, 132). Whenever and App needs to write or read something from disk, a template is added to the templates file to describe that location. Since Apps often are set up to form a pipeline, the output template of one App (e.g. a publishing app) is often the input template of another app (e.g. a loading app). This is why all the file system locations are kept in a single file.

The template API lets you jump between a list of field values and paths:

# get a template object from the API
>>> template_obj = sgtk.templates["maya_shot_publish"]
<Sgtk Template maya_asset_project: shots/{Shot}/{Step}/pub/{name}.v{version}.ma>

# we can use the template object to turn a path into a set of fields...
>>> path = '/projects/bbb/shots/001_002/comp/pub/main_scene.v003.ma'
>>> fields = template_obj.get_fields(path)

{'Shot': '001_002',
 'Step': 'comp',
 'name': 'main_scene',
 'version': 3}

# alternatively, we can take a fields dictionary and make a path
>>> template_obj.apply_fields(fields)
'/projects/bbb/shots/001_002/comp/pub/main_scene.v003.ma'

Note how the above path and template has two different types of fields: The Shot and Step fields are high-level fields with equivalent objects in Flow Production Tracking (a Shot and a Pipeline Step) where the name and the version fields are very specific to this particular type of template (in this case a publish path.). If we wanted to describe a publish path for an asset rather than a shot, we would still have a name and a version field, since this is needed for all publishes, regardless of what type of data it is - however, we would not have a Shot and a Step field. Instead, we may have an Asset and a Step field, where the asset field would be associated with an asset in Flow Production Tracking.

Template

class sgtk.Template(definition, keys, name=None)[source]

Represents an expression containing several dynamic tokens in the form of TemplateKey objects.

This class is not designed to be used directly but should be subclassed by any Template implementations.

Current implementations can be found in the TemplatePath and TemplateString classes.

Parameters:
  • definition (String) – Template definition.

  • keys (Dictionary) – Mapping of key names to keys

  • name (String) – (Optional) name for this template.

property definition

The template as a string, e.g shots/{Shot}/{Step}/pub/{name}.v{version}.ma

property keys

The keys that this template is using. For a template shots/{Shot}/{Step}/pub/{name}.v{version}.ma, the keys are {Shot}, {Step} and {name}.

Returns:

a dictionary of class:TemplateKey objects, keyed by token name.

property ordered_keys

The keys that this template is using in the order they appear. For a template shots/{Shot}/{Step}/pub/{name}.v{version}.ma, the keys are {Shot}, {Step} and {name}.

Returns:

a list of class:TemplateKey objects.

is_optional(key_name)[source]

Returns true if the given key name is optional for this template.

For the template {Shot}[_{name}], is_optional("Shot") would return False and is_optional("name") would return True

Parameters:

key_name – Name of template key for which the check should be carried out

Returns:

True if key is optional, False if not.

missing_keys(fields, skip_defaults=False)[source]

Determines keys required for use of template which do not exist in a given fields.

Example:

>>> tk.templates["max_asset_work"].missing_keys({})
['Step', 'sg_asset_type', 'Asset', 'version', 'name']

>>> tk.templates["max_asset_work"].missing_keys({"name": "foo"})
['Step', 'sg_asset_type', 'Asset', 'version']
Parameters:
  • fields (mapping (dictionary or other)) – fields to test

  • skip_defaults (Bool) – If true, do not treat keys with default values as missing.

Returns:

Fields needed by template which are not in inputs keys or which have values of None.

Return type:

list

apply_fields(fields, platform=None)[source]

Creates path using fields. Certain fields may be processed in special ways, for example SequenceKey fields, which can take a FORMAT string which will intelligently format a image sequence specifier based on the type of data is being handled. Example:

# get a template object from the API
>>> template_obj = sgtk.templates["maya_shot_publish"]
<Sgtk Template maya_asset_project: shots/{Shot}/{Step}/pub/{name}.v{version}.ma>

>>> fields = {'Shot': '001_002',
              'Step': 'comp',
              'name': 'main_scene',
              'version': 3
              }

>>> template_obj.apply_fields(fields)
'/projects/bbb/shots/001_002/comp/pub/main_scene.v003.ma'

Note

For formatting of special values, see SequenceKey and TimestampKey.

Example:

>>> fields = {"Sequence":"seq_1", "Shot":"shot_2", "Step":"comp", "name":"henry", "version":3}

>>> template_path.apply_fields(fields)
'/studio_root/sgtk/demo_project_1/sequences/seq_1/shot_2/comp/publish/henry.v003.ma'

>>> template_path.apply_fields(fields, platform='win32')
'z:\studio_root\sgtk\demo_project_1\sequences\seq_1\shot_2\comp\publish\henry.v003.ma'

>>> template_str.apply_fields(fields)
'Maya Scene henry, v003'
Parameters:
  • fields – Mapping of keys to fields. Keys must match those in template definition.

  • platform – Optional operating system platform. If you leave it at the default value of None, paths will be created to match the current operating system. If you pass in a sys.platform-style string (e.g. win32, linux2 or darwin), paths will be generated to match that platform.

Returns:

Full path, matching the template with the given fields inserted.

property parent

Returns Template representing the parent of this object.

Returns:

Template

validate_and_get_fields(path, required_fields=None, skip_keys=None)[source]

Takes an input string and determines whether it can be mapped to the template pattern. If it can then the list of matching fields is returned. Example:

>>> good_path = '/studio_root/sgtk/demo_project_1/sequences/seq_1/shot_2/comp/publish/henry.v003.ma'
>>> template_path.validate_and_get_fields(good_path)
{'Sequence': 'seq_1',
 'Shot': 'shot_2',
 'Step': 'comp',
 'name': 'henry',
 'version': 3}

>>> bad_path = '/studio_root/sgtk/demo_project_1/shot_2/comp/publish/henry.v003.ma'
>>> template_path.validate_and_get_fields(bad_path)
None
Parameters:
  • path – Path to validate

  • required_fields – An optional dictionary of key names to key values. If supplied these values must be present in the input path and found by the template.

  • skip_keys – List of field names whose values should be ignored

Returns:

Dictionary of fields found from the path or None if path fails to validate

validate(path, fields=None, skip_keys=None)[source]

Validates that a path can be mapped to the pattern given by the template. Example:

>>> good_path = '/studio_root/sgtk/demo_project_1/sequences/seq_1/shot_2/comp/publish/henry.v003.ma'
>>> template_path.validate(good_path)
True

>>> bad_path = '/studio_root/sgtk/demo_project_1/shot_2/comp/publish/henry.v003.ma'
>>> template_path.validate(bad_path)
False
Parameters:
  • path (String) – Path to validate

  • fields (Dictionary) – An optional dictionary of key names to key values. If supplied these values must be present in the input path and found by the template.

  • skip_keys (List) – Field names whose values should be ignored

Returns:

True if the path is valid for this template

Return type:

Bool

get_fields(input_path, skip_keys=None)[source]

Extracts key name, value pairs from a string. Example:

>>> input_path = '/studio_root/sgtk/demo_project_1/sequences/seq_1/shot_2/comp/publish/henry.v003.ma'
>>> template_path.get_fields(input_path)

{'Sequence': 'seq_1',
 'Shot': 'shot_2',
 'Step': 'comp',
 'name': 'henry',
 'version': 3}
Parameters:
  • input_path (String) – Source path for values

  • skip_keys (List) – Optional keys to skip

Returns:

Values found in the path based on keys in template

Return type:

Dictionary

TemplatePath

class sgtk.TemplatePath(definition, keys, root_path, name=None, per_platform_roots=None)[source]

Template representing a complete path on disk. The template definition is multi-platform and you can pass it per-os roots given by a separate root_path().

TemplatePath objects are typically created automatically by toolkit reading the template configuration.

Parameters:
  • definition – Template definition string.

  • keys – Mapping of key names to keys (dict)

  • root_path – Path to project root for this template.

  • name – Optional name for this template.

  • per_platform_roots – Root paths for all supported operating systems. This is a dictionary with sys.platform-style keys

property root_path

Returns the root path associated with this template.

property parent

Returns Template representing the parent of this object.

For paths, this means the parent folder.

Returns:

Template

TemplateString

class sgtk.TemplateString(definition, keys, name=None, validate_with=None)[source]

Template class for templates representing strings.

Templated strings are useful if you want to write code where you can configure the formatting of strings, for example how a name or other string field should be configured in Shotgun, given a series of key values.

TemplatePath objects are typically created automatically by toolkit reading the template configuration.

Parameters:
  • definition – Template definition string.

  • keys – Mapping of key names to keys (dict)

  • name – Optional name for this template.

  • validate_with – Optional Template to use for validation

property parent

Strings don’t have a concept of parent so this always returns None.

TemplateKey

A template, e.g. shots/{Shot}/{Step}/pub/{name}.v{version}.ma consists of several dynamic {tokens}. Each token is represented by a TemplateKey object at runtime, where you can access properties and execute token specific logic.

class sgtk.TemplateKey(name, default=None, choices=None, shotgun_entity_type=None, shotgun_field_name=None, exclusions=None, abstract=False, length=None)[source]

Base class for all template key types. Should not be used directly.

TemplateKeys are used by Template object to move between key values and resolved strings. The template keys handle the manner in which this conversion should occur. Template keys come in four flavors: string, integer, sequence and timestamp:

>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio.08/demo_project")


>>> template_path = tk.templates['nuke_asset_render']
# .../{name}/v{version}/{width}x{height}/{Asset}_{name}_{output}_{render_time}.{frame}.exr'

>>> str_key = template_path.keys['Asset']
>>> str_key
<Sgtk StringKey Asset>

>>> int_key = template_path.keys['height']
>>> int_key
<Sgtk IntegerKey height>

>>> seq_key = template_path.keys['frame']
>>> seq_key
<Sgtk SequenceKey frame>

>>> timestamp_key = template_path.keys['render_time']
>>> timestamp_key
<Sgtk TimestampKey render_time>
Parameters:
  • name (str) – Name by which the key will be referred.

  • default – Default value for this key. If the default is a callable, it will be invoked without any parameters whenever a default value is required.

  • choices – List of possible values for this key. Can be either a list or a dictionary of choice:label pairs.

  • shotgun_entity_type (str) – For keys directly linked to a shotgun field, the entity type.

  • shotgun_field_name (str) – For keys directly linked to a shotgun field, the field name.

  • exclusions (list) – List of forbidden values.

  • abstract (bool) – Flagging that this should be treated as an abstract key.

  • length (int) – If non-None, indicating that the value should be of a fixed length.

property default

The default value for this key. If the default argument was specified as a callable in the constructor, it is invoked and assumed to take no parameters.

Returns:

The default value.

property name

The name that the template will use to refer to the key.

property length

Fixed length that needs to be used for this item or None if any length is valid.

property shotgun_entity_type

Shotgun entity type associated with this item

property shotgun_field_name

Shotgun field name associated with this item

property exclusions

List of values which are not allowed for this item.

property is_abstract

A boolean value indicating if this key is abstract. Abstract keys are typically used in conjunction with path elements which represent clusters of files, for example when you want to represent a sequence of frames using a %04d syntax or a left and right eye using a %v syntax.

property choices

List of choices available, e.g. ['ma', 'mb']

property labelled_choices

Dictionary of labelled choices, e.g. {'ma': 'Maya Ascii', 'mb': 'Maya Binary'}

str_from_value(value=None, ignore_type=False)[source]

Returns a string version of a value as appropriate for the key’s setting.

Parameters:
  • value – Value to process. If None, the key’s default will be used.

  • ignore_type – If true, no validation will be carried out prior to casting.

Returns:

String version of value as processed by the key.

Raises:

TankError if value is not valid for the key.

value_from_str(str_value)[source]

Validates and translates a string into an appropriate value for this key.

Parameters:

str_value – The string to translate.

Returns:

The translated value.

validate(value)[source]

Test if a value is valid for this key:

>>> str_key.validate('foo')
True

>>> int_key.validate(2)
True

>>> int_key.validate('foo')
False

>>> seq_key.validate(3)
True

>>> seq_key.validate('foo')
False
Parameters:

value – Value to test

Returns:

Bool

StringKey

class sgtk.StringKey(name, default=None, choices=None, filter_by=None, shotgun_entity_type=None, shotgun_field_name=None, exclusions=None, abstract=False, length=None, subset=None, subset_format=None)[source]

TemplateKey representing a string value.

Parameters:
  • name (str) – Name by which the key will be referred.

  • default (str) – Default value for the key.

  • choices – List of possible values for this key. Can be either a list or a dictionary of choice:label pairs.

  • filter_by (str) – Name of filter type to limit values for string. Currently only accepted values are ‘alphanumeric’, ‘alpha’, None and a regex string.

  • shotgun_entity_type (str) – For keys directly linked to a shotgun field, the entity type.

  • shotgun_field_name (str) – For keys directly linked to a shotgun field, the field name.

  • exclusions (list) – List of forbidden values.

  • abstract (bool) – Flagging that this should be treated as an abstract key.

  • length (int) – If non-None, indicating that the value should be of a fixed length.

  • subset (str) – Regular expression defining a subset of the value to use.

  • subset_format (str) – String to express the formatting of subset tokens.

property filter_by

Name of filter type to limit values for string. alphanumeric, alpha, None or a regex string.

property subset

Returns a regular expression describing how values should be transformed when they are being injected into template paths and strings.

The format for a subset is a regular expression containing regex groups, for example:

# grabs capital letters of the two first words
user_initials:
    type: str
    subset: '([A-Z])[a-z]* ([A-Z])[a-z]*'

# extracts the first three characters
first_three_characters:
    type: str
    subset: '(.{3}).*'

# in code, the above expressions would compress the following input:

some_template.apply_fields(
    {"user_initials": "John Smith",
    "first_three_characters": "John Smith"}
)

# into "JS" for the {user_initials} key and "Joh" for the {first_three_characters} key

If the subset expression contains more than one (regex group) to extract, the groups will be concatenated together in the order they are found. If you want greater control over this, see subset_format().

property subset_format

Returns the subset_format string for the given template key. This string is used in conjunction with the subset() parameter and allows for the formatting of the values that are being extracted:

# grabs capital letters of the two first words
user_initials_backwards:
    type: str
    subset: '([A-Z])[a-z]* ([A-Z])[a-z]*'
    subset_format: '{1}{0}'

# in code, the above expression would compress the following input:

some_template.apply_fields({"user_initials": "John Smith"})

# into "SJ" for the user_initials_backwards key.

The formatting used for the string is standard python custom string formatting, where you can reference each regex group with an integer index. Read more about standard python string formatting here: https://docs.python.org/2/library/string.html#custom-string-formatting

Note

Subset format is using python string formatting and is only compatible with with Python 2.6+.

validate(value)[source]

Test if a value is valid for this key.

Parameters:

value – Value to test

Returns:

True if valid, false if not.

value_from_str(str_value)[source]

Validates and translates a string into an appropriate value for this key.

Parameters:

str_value – The string to translate.

Returns:

The translated value.

SequenceKey

class sgtk.SequenceKey(name, default=None, choices=None, format_spec='01', shotgun_entity_type=None, shotgun_field_name=None, exclusions=None)[source]

TemplateKey representing an integer sequence, usually used to handle frame sequences.

With image sequences, there are many ways of representing a set of images. Different applications use different representations, so it is often necessary to be able to extract image sequences on a particular format so that it works with a particular application environment.

In Toolkit, this can be done using a special FORMAT directive. This format directive only works with abstract image sequence fields and supports a number of different formats. For example, an app may need to reconstruct a path, but the app doesn’t know if the user has configured the input paths to use eight zero padded paths or four zero padded paths. However, the app runs in Nuke, so it needs path on the form %04d (for four zero padded paths). In order to get the correct padding, pass FORMAT: %d and Toolkit will format this with the correct padding.

The following conversions are supported for sequence keys:

  • FORMAT: %d - Turns format_spec 04 into %04d and a non-zero padded format_spec into %d

  • FORMAT: @ - Turns format_spec 04 into @@@@ and a non-zero padded format_spec into @

  • FORMAT: # - Turns format_spec 04 into #### and a non-zero padded format_spec into #

  • FORMAT: $F - Turns format_spec 04 into $F4 and a non-zero padded format_spec into $F

Example:

# An app in nuke generates a sequence path like this:
>>> fields = {"Shot":"shot_2", "name":"render", "seq": "FORMAT: %d"}
# the FORMAT field will correctly format the key regardless of
# how it has been configured (e.g. for any type of padding)
>>> template_path.apply_fields(fields)
'/mnt/proj/shot_2/publish/render.%04d.exr'


# in houdini, the code would look like this
>>> fields = {"Shot":"shot_2", "name":"render", "seq": "FORMAT: $F"}
# the FORMAT field will correctly format the key regardless of
# how it has been configured (e.g. for any type of padding)
>>> template_path.apply_fields(fields)
'/mnt/proj/shot_2/publish/render.$F4.exr'
Parameters:
  • name (str) – Name by which the key will be referred.

  • default (str) – Default value for this key.

  • choices (list) – List of possible values for this key.

  • format_spec (str) – Specification for formatting when casting to a string. The form is a zero followed the number of spaces to pad the value.

  • shotgun_entity_type (str) – For keys directly linked to a shotgun field, the entity type.

  • shotgun_field_name (str) – For keys directly linked to a shotgun field, the field name.

  • exclusions (str) – List of forbidden values.

validate(value)[source]

Test if a value is valid for this key:

>>> str_key.validate('foo')
True

>>> int_key.validate(2)
True

>>> int_key.validate('foo')
False

>>> seq_key.validate(3)
True

>>> seq_key.validate('foo')
False
Parameters:

value – Value to test

Returns:

Bool

IntegerKey

class sgtk.IntegerKey(name, default=None, choices=None, format_spec=None, shotgun_entity_type=None, shotgun_field_name=None, exclusions=None, abstract=False, length=None, strict_matching=None)[source]

TemplateKey representing an integer value.

Parameters:
  • name (str) – Name by which the key will be referred.

  • default (int) – Default value for this key.

  • choices (list) – List of possible values for this key.

  • format_spec (str) – Specification for formatting when casting to a string. The form is a zero followed the number of spaces to pad the value.

  • shotgun_entity_type (str) – For keys directly linked to a shotgun field, the entity type.

  • shotgun_field_name (str) – For keys directly linked to a shotgun field, the field name.

  • exclusions (list) – List of forbidden values.

  • abstract (bool) – Flagging that this should be treated as an abstract key.

  • length (int) – If non-None, indicating that the value should be of a fixed length.

  • strict_matching (bool) – Indicates if the padding should be matching exactly the format_spec when parsing a string. Default behavior is to match exactly the padding when a format_spec is provided.

property format_spec

Specification for formatting when casting to a string. The form is a zero followed the number of spaces to pad the value.

property strict_matching

Indicates if the padding should be matching exactly the format_spec when parsing a string.

validate(value)[source]

Test if a value is valid for this key:

>>> str_key.validate('foo')
True

>>> int_key.validate(2)
True

>>> int_key.validate('foo')
False

>>> seq_key.validate(3)
True

>>> seq_key.validate('foo')
False
Parameters:

value – Value to test

Returns:

Bool

TimestampKey

class sgtk.TimestampKey(name, default=None, format_spec='%Y-%m-%d-%H-%M-%S')[source]

TemplateKey representing a time or date string formatted with strftime.

Parameters:
  • name (str) – Name by which the key will be referred.

  • default

    Default value for this field. Acceptable values are:

    • None

    • a string formatted according to the format_spec, e.g. ‘2003-01-02 12:23’

    • utc_now, which means the current time in the UTC timezone will be used as the default value.

    • now, which means the current time in the local timezone will be used as the default value.

  • format_spec (str) – Specification for formatting when casting to/from a string. The format follows the convention of time.strftime(). The default value is %Y-%m-%d-%H-%M-%S. Given June 24th, 2015 at 9:20:30 PM, this will yield 2015-06-24-21-20-30.

property format_spec

Specification for formatting when casting to/from a string. The format follows the convention of time.strftime().

validate(value)[source]

Test if a value is valid for this key.

Parameters:

value – Value to test.

Returns:

Bool

Exceptions

The following exceptions are raised by the Toolkit Core API classes:

class sgtk.TankError[source]

Bases: Exception

Top level exception for all toolkit-core level runtime errors

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class sgtk.TankErrorProjectIsSetup[source]

Bases: TankError

Exception that indicates that a project already has a toolkit name but no pipeline configuration.

Include error message

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class sgtk.TankFileDoesNotExistError[source]

Bases: TankUnreadableFileError

Exception that indicates that a required file does not exist.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class sgtk.TankHookMethodDoesNotExistError[source]

Bases: TankError

Exception that indicates that a called method does not exist in the hook.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class sgtk.TankUnreadableFileError[source]

Bases: TankError

Exception that indicates that a required file can’t be read from disk.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class sgtk.TankInvalidCoreLocationError[source]

Bases: TankError

Exception that indicates the core location file contained an invalid path.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class sgtk.TankNotPipelineConfigurationError[source]

Bases: TankError

Exception that indicates that a folder doesn’t contain a pipeline configuration.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.