rez.rex#

class rez.rex.Action#

Bases: object

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

Bases: Action

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

Bases: EnvAction

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

Bases: EnvAction

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

Bases: EnvAction

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

Bases: Setenv

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

Bases: Setenv

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

Bases: Action

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

Bases: Action

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

Bases: Action

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

Bases: Action

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

Bases: Action

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

Bases: Action

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

Bases: Action

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

Bases: Action

name = 'shebang'#
__init__(*args)#
classmethod get_command_types()#
classmethod register()#
classmethod register_command_type(name, klass)#
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, parent_environ=None, parent_variables=None, formatter=None, verbose=False, env_sep_map=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)#
defined(key)#
expandvars(value, format=True)#
getenv(key)#
setenv(key, value)#
unsetenv(key)#
resetenv(key, value, friends=None)#
prependenv(key, value)#
appendenv(key, value)#
alias(key, value)#
info(value='')#
error(value)#
stop(msg, *nargs)#
command(value)#
comment(value)#
source(value)#
shebang()#
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)#

Returns any implementation specific data.

Parameters:

style (OutputStyle) – Style affecting output format.

Returns:

Depends on implementation, but usually a code string.

setenv(key, value)#
unsetenv(key)#
resetenv(key, value, friends=None)#
prependenv(key, value)#

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

appendenv(key, value)#

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

alias(key, value)#
info(value)#
error(value)#
command(value)#
comment(value)#
source(value)#
shebang()#
escape_string(value, is_path=False)#

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=False)#
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.

set_manager(manager)#
apply_environ()#

Apply changes to target environ.

get_output(style=OutputStyle.file)#

Returns any implementation specific data.

Parameters:

style (OutputStyle) – Style affecting output format.

Returns:

Depends on implementation, but usually a code string.

setenv(key, value)#
unsetenv(key)#
resetenv(key, value, friends=None)#
prependenv(key, value)#

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

appendenv(key, value)#

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

info(value)#
error(value)#
subprocess(args, **subproc_kwargs)#
command(value)#
comment(value)#
source(value)#
alias(key, value)#
shebang()#
get_key_token(key)#
adjust_env_for_platform(env)#

Make required platform-specific adjustments to env.

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

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, is_literal=False)#
copy()#
literal(value)#
expandable(value)#
l(value)#
e(value)#
expanduser()#

Analogous to os.path.expanduser.

Returns:

EscapedString object with expanded ‘~’ references.

formatted(func)#

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, values)#
classmethod promote(value)#
classmethod demote(value)#
classmethod disallow(value)#
rez.rex.literal(value)#

Creates a literal string.

rez.rex.expandable(value)#

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)#
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)#

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: 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)#
property name#
prepend(value)#
append(value)#
reset(value, friends=None)#
set(value)#
unset()#
get()#
value()#
setdefault(value)#

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=None, globals_map=None, parent_environ=None, parent_variables=None, shebang=True, add_default_namespaces=True)#
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#
property actions#

List of Action objects that will be executed.

bind(name, obj)#

Binds an object to the execution context.

Parameters:
  • name (str) –

  • obj (object) – Object to bind.

unbind(name)#

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()#

Append system paths to $PATH.

prepend_rez_path()#

Prepend rez path to $PATH.

append_rez_path()#

Append rez path to $PATH.

normalize_path(path)#

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)#

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)#