rez.rex

class rez.rex.Action

Bases: object

name: str
__init__(*args) None
classmethod register_command_type(name, klass) None
classmethod register() None
classmethod get_command_types()
class rez.rex.EnvAction

Bases: Action

property key: str
property value: str | None
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
name: str
class rez.rex.Unsetenv

Bases: EnvAction

name: str = 'unsetenv'
__init__(*args) None
classmethod get_command_types()
property key: str
classmethod register() None
classmethod register_command_type(name, klass) None
property value: str | None
class rez.rex.Setenv

Bases: EnvAction

name: str = 'setenv'
pre_exec(interpreter) None
post_exec(interpreter, result)
__init__(*args) None
classmethod get_command_types()
property key: str
classmethod register() None
classmethod register_command_type(name, klass) None
property value: str | None
class rez.rex.Resetenv

Bases: EnvAction

name: str = 'resetenv'
property friends
pre_exec(interpreter) None
post_exec(interpreter, result)
__init__(*args) None
classmethod get_command_types()
property key: str
classmethod register() None
classmethod register_command_type(name, klass) None
property value: str | None
class rez.rex.Prependenv

Bases: Setenv

name: str = 'prependenv'
__init__(*args) None
classmethod get_command_types()
property key: str
post_exec(interpreter, result)
pre_exec(interpreter) None
classmethod register() None
classmethod register_command_type(name, klass) None
property value: str | None
class rez.rex.Appendenv

Bases: Setenv

name: str = 'appendenv'
__init__(*args) None
classmethod get_command_types()
property key: str
post_exec(interpreter, result)
pre_exec(interpreter) None
classmethod register() None
classmethod register_command_type(name, klass) None
property value: str | None
class rez.rex.Alias

Bases: Action

name: str = 'alias'
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
class rez.rex.Info

Bases: Action

name: str = 'info'
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
class rez.rex.Error

Bases: Action

name: str = 'error'
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
class rez.rex.Stop

Bases: Action

name: str = 'stop'
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
class rez.rex.Command

Bases: Action

name: str = 'command'
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
class rez.rex.Comment

Bases: Action

name: str = 'comment'
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
class rez.rex.Source

Bases: Action

name: str = 'source'
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
class rez.rex.Shebang

Bases: Action

name: str = 'shebang'
__init__(*args) None
classmethod get_command_types()
classmethod register() None
classmethod register_command_type(name, klass) None
class rez.rex.OutputStyle

Bases: Enum

Enum to represent the style of code output when using Rex.

file = ('Code as it would appear in a script file.',)
eval = ('Code in a form that can be evaluated.',)
class rez.rex.ActionManager

Bases: object

Handles the execution book-keeping. Tracks env variable values, and triggers the callbacks of the ActionInterpreter.

__init__(interpreter: ActionInterpreter, parent_environ: Mapping[str, str] | None = None, parent_variables: Iterable[str] | None = None, formatter=None, verbose: bool = False, env_sep_map=None) None
interpreter: string or ActionInterpreter

the interpreter to use when executing rex actions

parent_environ: environment to execute the actions within. If None,

defaults to the current environment.

parent_variables: List of variables to append/prepend to, rather than

overwriting on first reference. If this is set to True instead of a list, all variables are treated as parent variables.

formatter: func or None

function to use for formatting string values

verbosebool or list of str

if True, causes commands to print additional feedback (using info()). can also be set to a list of strings matching command names to add verbosity to only those commands.

get_action_methods()

return a list of methods on this class for executing actions. methods are return as a list of (name, func) tuples

get_public_methods()

return a list of methods on this class which should be exposed in the rex API.

get_output(style=OutputStyle.file)
undefined(key) bool
defined(key) bool
expandvars(value, format: bool = True) str
getenv(key)
setenv(key, value) None
unsetenv(key) None
resetenv(key, value, friends=None) None
prependenv(key, value) None
appendenv(key, value) None
alias(key, value) None
info(value='') None
error(value) None
stop(msg, *nargs)
command(value) None
comment(value) None
source(value) None
shebang() None
class rez.rex.ActionInterpreter

Bases: object

Abstract base class that provides callbacks for rex Actions. This class should not be used directly. Its methods are called by the ActionManager in response to actions issued by user code written using the rex python API.

Sub-classes should override the get_output method to return implementation-specific data structure. For example, an interpreter for a shell language like bash would return a string of shell code. An interpreter for an active python session might return a dictionary of the modified environment.

Sub-classes can override the expand_env_vars class variable to instruct the ActionManager whether or not to expand the value of environment variables which reference other variables (e.g. “this-${THAT}”).

expand_env_vars = False
pathsep = ':'
ENV_VAR_REGEX = re.compile('\\${([^\\{\\}]+?)}|\\$([a-zA-Z_]+[a-zA-Z0-9_]*?)')
get_output(style=OutputStyle.file) Any

Returns any implementation specific data.

Parameters:

style (OutputStyle) – Style affecting output format.

Returns:

Depends on implementation, but usually a code string.

setenv(key: str, value: str | EscapedString)
unsetenv(key: str)
resetenv(key, value, friends=None)
prependenv(key, value: str | EscapedString)

This is optional, but if it is not implemented, you must implement setenv.

appendenv(key, value: str | EscapedString)

This is optional, but if it is not implemented, you must implement setenv.

alias(key, value)
info(value: str)
error(value: str)
command(value)
comment(value: str)
source(value)
shebang()
get_key_token(key) str
escape_string(value: str | EscapedString, is_path: bool = False) str

Escape a string.

Escape the given string so that special characters (such as quotes and whitespace) are treated properly. If value is a string, assume that this is an expandable string in this interpreter.

Note that is_path provided because of the special case where a path-like envvar is set. In this case, path normalization, if it needs to occur, has to be part of the string escaping process.

Note

This default implementation returns the string with no escaping applied.

Parameters:
  • value (str or EscapedString) – String to escape.

  • is_path (bool) – True if the value is path-like.

Returns:

The escaped string.

Return type:

str

normalize_path(path)

Normalize a path.

Change path to a valid filepath representation for this interpreter.

IMPORTANT: Because var references like ${THIS} might be passed to funcs like appendvar, path might be in this form. You need to take that into account (ie, ensure normalization doesn’t break such a var reference).

Parameters:

path (str) – A filepath which may be in posix format, or windows format, or some combination of the two. For eg, a string like {root}/bin on windows will evaluate to C:.../bin - in this case, the cmd shell would want to normalize this and convert to all forward slashes.

Returns:

The normalized path.

Return type:

str

normalize_paths(value)

Normalize value if it’s a path(s).

Note that value may be more than one pathsep-delimited paths.

class rez.rex.Python

Bases: ActionInterpreter

Execute commands in the current python session

expand_env_vars = True
__init__(target_environ=None, passive: bool = False) None
target_environ: dict

If target_environ is None or os.environ, interpreted actions are applied to the current python interpreter. Otherwise, changes are only applied to target_environ. In either case you must call apply_environ to flush all changes to the target environ dict.

passive: bool

If True, commands that do not update the environment (such as info) are skipped.

manager: ActionManager | None
set_manager(manager: ActionManager) None
apply_environ() None

Apply changes to target environ.

get_output(style=OutputStyle.file) dict[str, str]

Returns any implementation specific data.

Parameters:

style (OutputStyle) – Style affecting output format.

Returns:

Depends on implementation, but usually a code string.

setenv(key, value: str | EscapedString) None
unsetenv(key) None
resetenv(key, value, friends=None) None
prependenv(key, value: str | EscapedString) None

This is optional, but if it is not implemented, you must implement setenv.

appendenv(key, value: str | EscapedString) None

This is optional, but if it is not implemented, you must implement setenv.

info(value) None
error(value) None
subprocess(args: str | Iterable[str], **subproc_kwargs) Popen
command(value)
comment(value) None
source(value) None
alias(key, value) None
shebang() None
get_key_token(key) str
adjust_env_for_platform(env) None

Make required platform-specific adjustments to env.

ENV_VAR_REGEX = re.compile('\\${([^\\{\\}]+?)}|\\$([a-zA-Z_]+[a-zA-Z0-9_]*?)')
escape_string(value: str | EscapedString, is_path: bool = False) str

Escape a string.

Escape the given string so that special characters (such as quotes and whitespace) are treated properly. If value is a string, assume that this is an expandable string in this interpreter.

Note that is_path provided because of the special case where a path-like envvar is set. In this case, path normalization, if it needs to occur, has to be part of the string escaping process.

Note

This default implementation returns the string with no escaping applied.

Parameters:
  • value (str or EscapedString) – String to escape.

  • is_path (bool) – True if the value is path-like.

Returns:

The escaped string.

Return type:

str

normalize_path(path)

Normalize a path.

Change path to a valid filepath representation for this interpreter.

IMPORTANT: Because var references like ${THIS} might be passed to funcs like appendvar, path might be in this form. You need to take that into account (ie, ensure normalization doesn’t break such a var reference).

Parameters:

path (str) – A filepath which may be in posix format, or windows format, or some combination of the two. For eg, a string like {root}/bin on windows will evaluate to C:.../bin - in this case, the cmd shell would want to normalize this and convert to all forward slashes.

Returns:

The normalized path.

Return type:

str

normalize_paths(value)

Normalize value if it’s a path(s).

Note that value may be more than one pathsep-delimited paths.

pathsep = ':'
class rez.rex.EscapedString

Bases: object

Class for constructing literal or expandable strings, or a combination of both.

This determines how a string is escaped in an interpreter. For example, the following rex commands may result in the bash code shown:

>>> env.FOO = literal('oh "noes"')
>>> env.BAH = expandable('oh "noes"')
export FOO='oh "noes"'
export BAH="oh "noes""

You do not need to use expandable - a string by default is interpreted as expandable. However you can mix literals and expandables together, like so:

>>> env.FOO = literal("hello").expandable(" ${DUDE}")
export FOO='hello'" ${DUDE}"

Shorthand methods e and l are also supplied, for better readability:

>>> env.FOO = literal("hello").e(" ${DUDE}").l(", and welcome!")
export FOO='hello'" ${DUDE}"', and welcome!'

Note

you can use the literal and expandable free functions, rather than constructing a class instance directly.

__init__(value: str, is_literal: bool = False) None
copy() EscapedString
literal(value) EscapedString
expandable(value) EscapedString
l(value)
e(value)
expanduser() EscapedString

Analogous to os.path.expanduser.

Returns:

EscapedString object with expanded ‘~’ references.

formatted(func) EscapedString

Return the string with non-literal parts formatted.

Parameters:

func (Callable) – Callable that translates a string into a formatted string.

Returns:

EscapedString object.

split(delimiter=None)

Same as string.split(), but retains literal/expandable structure.

Returns:

List of EscapedString.

classmethod join(sep: str, values) EscapedString
classmethod promote(value: str | EscapedString) EscapedString
classmethod demote(value: str | EscapedString) str
classmethod disallow(value)
rez.rex.literal(value) EscapedString

Creates a literal string.

rez.rex.expandable(value) EscapedString

Creates an expandable string.

rez.rex.optionvars(name, default=None)

Access arbitrary data from rez config setting ‘optionvars’.

Parameters:
  • name (str) – Name of the optionvar. Use dot notation for values in nested dicts.

  • default (object) – Default value if setting is missing.

class rez.rex.NamespaceFormatter

Bases: Formatter

String formatter that, as well as expanding ‘{variable}’ strings, also protects environment variable references such as ${THIS} so they do not get expanded as though {THIS} is a formatting target. Also, environment variable references such as $THIS are converted to ${THIS}, which gives consistency across shells, and avoids some problems with non-curly-braced variables in some situations.

__init__(namespace) None
format(format_string, *args, **kwargs)
format_field(value, format_spec)
get_value(key, args, kwds)
check_unused_args(used_args, args, kwargs)
convert_field(value, conversion)
get_field(field_name, args, kwargs)
parse(format_string)
vformat(format_string, args, kwargs)
class rez.rex.EnvironmentDict

Bases: MutableMapping

Provides a mapping interface to EnvironmentVariable instances, which provide an object-oriented interface for recording environment variable manipulations.

__getitem__ is always guaranteed to return an EnvironmentVariable instance: it will not raise a KeyError.

__init__(manager) None

Creates an EnvironmentDict.

Parameters:

override_existing_lists (bool) – If True, the first call to append or prepend will override the value in environ and effectively act as a setenv operation. If False, pre-existing values will be appended/prepended to as usual.

keys() a set-like object providing a view on D's keys
clear() None.  Remove all items from D.
get(k[, d]) D[k] if k in D, else d.  d defaults to None.
items() a set-like object providing a view on D's items
pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E.keys(): D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() an object providing a view on D's values
class rez.rex.EnvironmentVariable

Bases: object

class representing an environment variable

combined with EnvironmentDict class, records changes to the environment

__init__(name, environ_map) None
property name
prepend(value) None
append(value) None
reset(value, friends=None) None
set(value) None
unset() None
get()
value()
setdefault(value) None

set value if the variable does not yet exist

class rez.rex.RexExecutor

Bases: object

Runs an interpreter over code within the given namespace. You can also access namespaces and rex functions directly in the executor, like so:

RexExecutor ex() ex.setenv(‘FOO’, ‘BAH’) ex.env.FOO_SET = 1 ex.alias(‘foo’,’foo -l’)

__init__(interpreter: ActionInterpreter | None = None, globals_map=None, parent_environ: Mapping[str, str] | None = None, parent_variables=None, shebang: bool = True, add_default_namespaces: bool = True) None
interpreter: ActionInterpreter or None

the interpreter to use when executing rex actions. If None, creates a python interpreter with an empty target environment dict.

globals_mapdict or None

dictionary which comprises the main python namespace when rex code is executed (via the python exec statement). if None, defaults to empty dict.

parent_environ: environment to execute the rex code within. If None, defaults

to the current environment.

parent_variables: List of variables to append/prepend to, rather than

overwriting on first reference. If this is set to True instead of a list, all variables are treated as parent variables.

shebang: bool

if True, apply a shebang to the result.

add_default_namespaces: bool

whether to add default namespaces such as ‘system’.

property interpreter: ActionInterpreter
property actions: list[Action]

List of Action objects that will be executed.

bind(name, obj) None

Binds an object to the execution context.

Parameters:
  • name (str)

  • obj (object) – Object to bind.

unbind(name: str) None

Unbind an object from the execution context.

Has no effect if the binding does not exist.

Parameters:

name (str)

reset_globals()

Remove changes to globals dict post-context.

Any bindings (self.bind) will only be visible during this context.

append_system_paths() None

Append system paths to $PATH.

prepend_rez_path() None

Prepend rez path to $PATH.

append_rez_path() None

Append rez path to $PATH.

normalize_path(path: str) str

Normalize a path.

Note that in many interpreters this will be unchanged.

Returns:

The normalized path.

Return type:

str

classmethod compile_code(code, filename=None, exec_namespace=None)

Compile and possibly execute rex code.

Parameters:
  • code (str or SourceCode) – The python code to compile.

  • filename (str) – File to associate with the code, will default to ‘<string>’.

  • exec_namespace (dict) – Namespace to execute the code in. If None, the code is not executed.

Returns:

Compiled code object.

execute_code(code, filename=None) None

Execute code within the execution context.

Parameters:
  • code (str or SourceCode) – Rex code to execute.

  • filename (str) – Filename to report if there are syntax errors.

execute_function(func, *nargs, **kwargs)

Execute a function object within the execution context. @returns The result of the function call.

get_output(style=OutputStyle.file)

Returns the result of all previous calls to execute_code.

expand(value)