INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Used by functions in package.py to have access to named modules. See the 'package_definition_python_path' config setting for more info.
def include(module_name, *module_names): """Used by functions in package.py to have access to named modules. See the 'package_definition_python_path' config setting for more info. """ def decorated(fn): _add_decorator(fn, "include", nargs=[module_name] + list(module_names)) return fn ...
Iterate over package families, in no particular order. Note that multiple package families with the same name can be returned. Unlike packages, families later in the searchpath are not hidden by earlier families. Args: paths (list of str, optional): paths to search for package families, ...
def iter_package_families(paths=None): """Iterate over package families, in no particular order. Note that multiple package families with the same name can be returned. Unlike packages, families later in the searchpath are not hidden by earlier families. Args: paths (list of str, optional)...
Iterate over `Package` instances, in no particular order. Packages of the same name and version earlier in the search path take precedence - equivalent packages later in the paths are ignored. Packages are not returned in any specific order. Args: name (str): Name of the package, eg 'maya'. ...
def iter_packages(name, range_=None, paths=None): """Iterate over `Package` instances, in no particular order. Packages of the same name and version earlier in the search path take precedence - equivalent packages later in the paths are ignored. Packages are not returned in any specific order. Arg...
Get an exact version of a package. Args: name (str): Name of the package, eg 'maya'. version (Version or str): Version of the package, eg '1.0.0' paths (list of str, optional): paths to search for package, defaults to `config.packages_path`. Returns: `Package` objec...
def get_package(name, version, paths=None): """Get an exact version of a package. Args: name (str): Name of the package, eg 'maya'. version (Version or str): Version of the package, eg '1.0.0' paths (list of str, optional): paths to search for package, defaults to `config.pa...
Create a package given its handle (or serialized dict equivalent) Args: package_handle (`ResourceHandle` or dict): Resource handle, or equivalent serialized dict representation from ResourceHandle.to_dict Returns: `Package`.
def get_package_from_handle(package_handle): """Create a package given its handle (or serialized dict equivalent) Args: package_handle (`ResourceHandle` or dict): Resource handle, or equivalent serialized dict representation from ResourceHandle.to_dict Returns: `Pac...
Get a package given a string. Args: txt (str): String such as 'foo', 'bah-1.3'. paths (list of str, optional): paths to search for package, defaults to `config.packages_path`. Returns: `Package` instance, or None if no package was found.
def get_package_from_string(txt, paths=None): """Get a package given a string. Args: txt (str): String such as 'foo', 'bah-1.3'. paths (list of str, optional): paths to search for package, defaults to `config.packages_path`. Returns: `Package` instance, or None if no pa...
Create a developer package. Args: path (str): Path to dir containing package definition file. format (str): Package definition file format, detected if None. Returns: `DeveloperPackage`.
def get_developer_package(path, format=None): """Create a developer package. Args: path (str): Path to dir containing package definition file. format (str): Package definition file format, detected if None. Returns: `DeveloperPackage`. """ from rez.developer_package import ...
Create a package given package data. Args: name (str): Package name. data (dict): Package data. Must conform to `package_maker.package_schema`. Returns: `Package` object.
def create_package(name, data, package_cls=None): """Create a package given package data. Args: name (str): Package name. data (dict): Package data. Must conform to `package_maker.package_schema`. Returns: `Package` object. """ from rez.package_maker__ import PackageMaker ...
Create a variant given its handle (or serialized dict equivalent) Args: variant_handle (`ResourceHandle` or dict): Resource handle, or equivalent serialized dict representation from ResourceHandle.to_dict context (`ResolvedContext`): The context this variant is associated ...
def get_variant(variant_handle, context=None): """Create a variant given its handle (or serialized dict equivalent) Args: variant_handle (`ResourceHandle` or dict): Resource handle, or equivalent serialized dict representation from ResourceHandle.to_dict context (`Resolv...
Returns the most recent time this package was released. Note that releasing a variant into an already-released package is also considered a package release. Returns: int: Epoch time of last package release, or zero if this cannot be determined.
def get_last_release_time(name, paths=None): """Returns the most recent time this package was released. Note that releasing a variant into an already-released package is also considered a package release. Returns: int: Epoch time of last package release, or zero if this cannot be deter...
Get autocompletion options given a prefix string. Example: >>> get_completions("may") set(["maya", "maya_utils"]) >>> get_completions("maya-") set(["maya-2013.1", "maya-2015.0.sp1"]) Args: prefix (str): Prefix to match. paths (list of str): paths to search for ...
def get_completions(prefix, paths=None, family_only=False): """Get autocompletion options given a prefix string. Example: >>> get_completions("may") set(["maya", "maya_utils"]) >>> get_completions("maya-") set(["maya-2013.1", "maya-2015.0.sp1"]) Args: prefix (str):...
Iterate over the packages within this family, in no particular order. Returns: `Package` iterator.
def iter_packages(self): """Iterate over the packages within this family, in no particular order. Returns: `Package` iterator. """ for package in self.repository.iter_packages(self.resource): yield Package(package)
Returns True if the package is in the local package repository
def is_local(self): """Returns True if the package is in the local package repository""" local_repo = package_repository_manager.get_repository( self.config.local_packages_path) return (self.resource._repository.uid == local_repo.uid)
Print the contents of the package. Args: buf (file-like object): Stream to write to. format_ (`FileFormat`): Format to write in. skip_attributes (list of str): List of attributes to not print. include_release (bool): If True, include release-related attributes, ...
def print_info(self, buf=None, format_=FileFormat.yaml, skip_attributes=None, include_release=False): """Print the contents of the package. Args: buf (file-like object): Stream to write to. format_ (`FileFormat`): Format to write in. skip_attribute...
Get the qualified name of the package. Returns: str: Name of the package with version, eg "maya-2016.1".
def qualified_name(self): """Get the qualified name of the package. Returns: str: Name of the package with version, eg "maya-2016.1". """ o = VersionedObject.construct(self.name, self.version) return str(o)
Get the parent package family. Returns: `PackageFamily`.
def parent(self): """Get the parent package family. Returns: `PackageFamily`. """ family = self.repository.get_parent_package_family(self.resource) return PackageFamily(family) if family else None
Iterate over the variants within this package, in index order. Returns: `Variant` iterator.
def iter_variants(self): """Iterate over the variants within this package, in index order. Returns: `Variant` iterator. """ for variant in self.repository.iter_variants(self.resource): yield Variant(variant, context=self.context, parent=self)
Get the variant with the associated index. Returns: `Variant` object, or None if no variant with the given index exists.
def get_variant(self, index=None): """Get the variant with the associated index. Returns: `Variant` object, or None if no variant with the given index exists. """ for variant in self.iter_variants(): if variant.index == index: return variant
Get the qualified name of the variant. Returns: str: Name of the variant with version and index, eg "maya-2016.1[1]".
def qualified_name(self): """Get the qualified name of the variant. Returns: str: Name of the variant with version and index, eg "maya-2016.1[1]". """ idxstr = '' if self.index is None else str(self.index) return "%s[%s]" % (self.qualified_package_name, idxstr)
Get the parent package. Returns: `Package`.
def parent(self): """Get the parent package. Returns: `Package`. """ if self._parent is not None: return self._parent try: package = self.repository.get_parent_package(self.resource) self._parent = Package(package, context=self.co...
Get the requirements of the variant. Args: build_requires (bool): If True, include build requirements. private_build_requires (bool): If True, include private build requirements. Returns: List of `Requirement` objects.
def get_requires(self, build_requires=False, private_build_requires=False): """Get the requirements of the variant. Args: build_requires (bool): If True, include build requirements. private_build_requires (bool): If True, include private build requirements. ...
Install this variant into another package repository. If the package already exists, this variant will be correctly merged into the package. If the variant already exists in this package, the existing variant is returned. Args: path (str): Path to destination package reposi...
def install(self, path, dry_run=False, overrides=None): """Install this variant into another package repository. If the package already exists, this variant will be correctly merged into the package. If the variant already exists in this package, the existing variant is returned. ...
Writes both to given filepath, and tmpdir location. This is to get around the problem with some NFS's where immediately reading a file that has just been written is problematic. Instead, any files that we write, we also write to /tmp, and reads of these files are redirected there. Args: filepa...
def open_file_for_write(filepath, mode=None): """Writes both to given filepath, and tmpdir location. This is to get around the problem with some NFS's where immediately reading a file that has just been written is problematic. Instead, any files that we write, we also write to /tmp, and reads of these ...
Load data from a file. Note: Any functions from a .py file will be converted to `SourceCode` objects. Args: filepath (str): File to load. format_ (`FileFormat`): Format of file contents. update_data_callback (callable): Used to change data before it is returned or c...
def load_from_file(filepath, format_=FileFormat.py, update_data_callback=None, disable_memcache=False): """Load data from a file. Note: Any functions from a .py file will be converted to `SourceCode` objects. Args: filepath (str): File to load. format_ (`FileForm...
Load python-formatted data from a stream. Args: stream (file-like object). Returns: dict.
def load_py(stream, filepath=None): """Load python-formatted data from a stream. Args: stream (file-like object). Returns: dict. """ with add_sys_paths(config.package_definition_build_python_paths): return _load_py(stream, filepath=filepath)
Replace certain values in the given package data dict. Does things like: * evaluates @early decorated functions, and replaces with return value; * converts functions into `SourceCode` instances so they can be serialized out to installed packages, and evaluated later; * strips some values (modules...
def process_python_objects(data, filepath=None): """Replace certain values in the given package data dict. Does things like: * evaluates @early decorated functions, and replaces with return value; * converts functions into `SourceCode` instances so they can be serialized out to installed packages...
Load yaml-formatted data from a stream. Args: stream (file-like object). Returns: dict.
def load_yaml(stream, **kwargs): """Load yaml-formatted data from a stream. Args: stream (file-like object). Returns: dict. """ # if there's an error parsing the yaml, and you pass yaml.load a string, # it will print lines of context, but will print "<string>" instead of a ...
Request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender pro...
def _close(self, args): """Request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to a...
RabbitMQ Extension.
def _blocked(self, args): """RabbitMQ Extension.""" reason = args.read_shortstr() if self.on_blocked: return self.on_blocked(reason)
Security mechanism response This method attempts to authenticate, passing a block of SASL data for the security mechanism at the server side. PARAMETERS: response: longstr security response data A block of opaque data passed to the security ...
def _x_secure_ok(self, response): """Security mechanism response This method attempts to authenticate, passing a block of SASL data for the security mechanism at the server side. PARAMETERS: response: longstr security response data A block ...
Select security mechanism and locale This method selects a SASL security mechanism. ASL uses SASL (RFC2222) to negotiate authentication and encryption. PARAMETERS: client_properties: table client properties mechanism: shortstr selected...
def _x_start_ok(self, client_properties, mechanism, response, locale): """Select security mechanism and locale This method selects a SASL security mechanism. ASL uses SASL (RFC2222) to negotiate authentication and encryption. PARAMETERS: client_properties: table ...
Propose connection tuning parameters This method proposes a set of connection configuration values to the client. The client can accept and/or adjust these. PARAMETERS: channel_max: short proposed maximum channels The maximum total number of chann...
def _tune(self, args): """Propose connection tuning parameters This method proposes a set of connection configuration values to the client. The client can accept and/or adjust these. PARAMETERS: channel_max: short proposed maximum channels ...
Send heartbeat packets, if necessary, and fail if none have been received recently. This should be called frequently, on the order of once per second. :keyword rate: Ignored
def heartbeat_tick(self, rate=2): """Send heartbeat packets, if necessary, and fail if none have been received recently. This should be called frequently, on the order of once per second. :keyword rate: Ignored """ if not self.heartbeat: return # tr...
Negotiate connection tuning parameters This method sends the client's connection tuning parameters to the server. Certain fields are negotiated, others provide capability information. PARAMETERS: channel_max: short negotiated maximum channels ...
def _x_tune_ok(self, channel_max, frame_max, heartbeat): """Negotiate connection tuning parameters This method sends the client's connection tuning parameters to the server. Certain fields are negotiated, others provide capability information. PARAMETERS: channel_ma...
Get the current parent suite. A parent suite exists when a context within a suite is active. That is, during execution of a tool within a suite, or after a user has entered an interactive shell in a suite context, for example via the command- line syntax 'tool +i', where 'tool' is an al...
def parent_suite(self): """Get the current parent suite. A parent suite exists when a context within a suite is active. That is, during execution of a tool within a suite, or after a user has entered an interactive shell in a suite context, for example via the command- line synt...
Print a status message about the given object. If an object is not provided, status info is shown about the current environment - what the active context is if any, and what suites are visible. Args: obj (str): String which may be one of the following: - A t...
def print_info(self, obj=None, buf=sys.stdout): """Print a status message about the given object. If an object is not provided, status info is shown about the current environment - what the active context is if any, and what suites are visible. Args: obj (str): Stri...
Print a list of visible tools. Args: pattern (str): Only list tools that match this glob pattern.
def print_tools(self, pattern=None, buf=sys.stdout): """Print a list of visible tools. Args: pattern (str): Only list tools that match this glob pattern. """ seen = set() rows = [] context = self.context if context: data = context.get_too...
Load a developer package. A developer package may for example be a package.yaml or package.py in a user's source directory. Args: path: Directory containing the package definition file, or file path for the package file itself format: which FileFormat to...
def from_path(cls, path, format=None): """Load a developer package. A developer package may for example be a package.yaml or package.py in a user's source directory. Args: path: Directory containing the package definition file, or file path for the package f...
Returns: (DeveloperPackage, new_data) 2-tuple IFF the preprocess function changed the package; otherwise None.
def _get_preprocessed(self, data): """ Returns: (DeveloperPackage, new_data) 2-tuple IFF the preprocess function changed the package; otherwise None. """ from rez.serialise import process_python_objects from rez.utils.data_utils import get_dict_diff_str ...
Parse the first YAML document in a stream and produce the corresponding Python object.
def load(stream, Loader=Loader): """ Parse the first YAML document in a stream and produce the corresponding Python object. """ loader = Loader(stream) try: return loader.get_single_data() finally: loader.dispose()
Parse all YAML documents in a stream and produce corresponding Python objects.
def load_all(stream, Loader=Loader): """ Parse all YAML documents in a stream and produce corresponding Python objects. """ loader = Loader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose()
Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead.
def dump_all(documents, stream=None, Dumper=Dumper, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding='utf-8', explicit_start=None, explicit_end=None, version=None, tags=None): """ Serialize...
Get a list of running instances. Args: context (`ResolvedContext`): Context the process is running in. process_name (str): Name of the process. Returns: List of (`subprocess.Popen`, start-time) 2-tuples, where start_time is the epoch time the process was...
def running_instances(self, context, process_name): """Get a list of running instances. Args: context (`ResolvedContext`): Context the process is running in. process_name (str): Name of the process. Returns: List of (`subprocess.Popen`, start-time) 2-tuples,...
return a list of methods on this class for executing actions. methods are return as a list of (name, func) tuples
def get_action_methods(self): """ return a list of methods on this class for executing actions. methods are return as a list of (name, func) tuples """ return [(name, getattr(self, name)) for name, _ in Action.get_command_types()]
return a list of methods on this class which should be exposed in the rex API.
def get_public_methods(self): """ return a list of methods on this class which should be exposed in the rex API. """ return self.get_action_methods() + [ ('getenv', self.getenv), ('expandvars', self.expandvars), ('defined', self.defined), ...
Apply changes to target environ.
def apply_environ(self): """Apply changes to target environ. """ if self.manager is None: raise RezSystemError("You must call 'set_manager' on a Python rex " "interpreter before using it.") self.target_environ.update(self.manager.environ)
Return the string with non-literal parts formatted. Args: func (callable): Callable that translates a string into a formatted string. Returns: `EscapedString` object.
def formatted(self, func): """Return the string with non-literal parts formatted. Args: func (callable): Callable that translates a string into a formatted string. Returns: `EscapedString` object. """ other = EscapedString.__new__(Escaped...
Same as string.split(), but retains literal/expandable structure. Returns: List of `EscapedString`.
def split(self, delimiter=None): """Same as string.split(), but retains literal/expandable structure. Returns: List of `EscapedString`. """ result = [] strings = self.strings[:] current = None while strings: is_literal, value = strings[0]...
Append system paths to $PATH.
def append_system_paths(self): """Append system paths to $PATH.""" from rez.shells import Shell, create_shell sh = self.interpreter if isinstance(self.interpreter, Shell) \ else create_shell() paths = sh.get_syspaths() paths_str = os.pathsep.join(paths) self....
Prepend rez path to $PATH.
def prepend_rez_path(self): """Prepend rez path to $PATH.""" if system.rez_bin_path: self.env.PATH.prepend(system.rez_bin_path)
Append rez path to $PATH.
def append_rez_path(self): """Append rez path to $PATH.""" if system.rez_bin_path: self.env.PATH.append(system.rez_bin_path)
Compile and possibly execute rex code. Args: 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, t...
def compile_code(cls, code, filename=None, exec_namespace=None): """Compile and possibly execute rex code. Args: code (str or SourceCode): The python code to compile. filename (str): File to associate with the code, will default to '<string>'. exec_na...
Execute code within the execution context. Args: code (str or SourceCode): Rex code to execute. filename (str): Filename to report if there are syntax errors. isolate (bool): If True, do not affect `self.globals` by executing this code.
def execute_code(self, code, filename=None, isolate=False): """Execute code within the execution context. Args: code (str or SourceCode): Rex code to execute. filename (str): Filename to report if there are syntax errors. isolate (bool): If True, do not affect `self....
Execute a function object within the execution context. @returns The result of the function call.
def execute_function(self, func, *nargs, **kwargs): """ Execute a function object within the execution context. @returns The result of the function call. """ # makes a copy of the func import types fn = types.FunctionType(func.func_code, ...
Returns the result of all previous calls to execute_code.
def get_output(self, style=OutputStyle.file): """Returns the result of all previous calls to execute_code.""" return self.manager.get_output(style=style)
Configure the filter. @type graph: graph @param graph: Graph. @type spanning_tree: dictionary @param spanning_tree: Spanning tree.
def configure(self, graph, spanning_tree): """ Configure the filter. @type graph: graph @param graph: Graph. @type spanning_tree: dictionary @param spanning_tree: Spanning tree. """ self.graph = graph self.spanning_tree = spanni...
Same as iter_packages in packages.py, but also applies this filter. Args: name (str): Name of the package, eg 'maya'. range_ (VersionRange or str): If provided, limits the versions returned to those in `range_`. paths (list of str, optional): paths to search ...
def iter_packages(self, name, range_=None, paths=None): """Same as iter_packages in packages.py, but also applies this filter. Args: name (str): Name of the package, eg 'maya'. range_ (VersionRange or str): If provided, limits the versions returned to those in `r...
Return a shallow copy of the filter. Adding rules to the copy will not alter the source.
def copy(self): """Return a shallow copy of the filter. Adding rules to the copy will not alter the source. """ other = PackageFilter.__new__(PackageFilter) other._excludes = self._excludes.copy() other._includes = self._includes.copy() return other
Get the approximate cost of this filter. Cost is the total cost of the exclusion rules in this filter. The cost of family-specific filters is divided by 10. Returns: float: The approximate cost of the filter.
def cost(self): """Get the approximate cost of this filter. Cost is the total cost of the exclusion rules in this filter. The cost of family-specific filters is divided by 10. Returns: float: The approximate cost of the filter. """ total = 0.0 for fa...
Add a filter to the list. Args: package_filter (`PackageFilter`): Filter to add.
def add_filter(self, package_filter): """Add a filter to the list. Args: package_filter (`PackageFilter`): Filter to add. """ filters = self.filters + [package_filter] self.filters = sorted(filters, key=lambda x: x.cost)
Return a copy of the filter list. Adding rules to the copy will not alter the source.
def copy(self): """Return a copy of the filter list. Adding rules to the copy will not alter the source. """ other = PackageFilterList.__new__(PackageFilterList) other.filters = [x.copy() for x in self.filters] return other
Parse a rule from a string. See rezconfig.package_filter for an overview of valid strings. Args: txt (str): String to parse. Returns: `Rule` instance.
def parse_rule(cls, txt): """Parse a rule from a string. See rezconfig.package_filter for an overview of valid strings. Args: txt (str): String to parse. Returns: `Rule` instance. """ types = {"glob": GlobRule, "regex": RegexRul...
Read n bytes.
def read(self, n): """Read n bytes.""" self.bitcount = self.bits = 0 return self.input.read(n)
Read a single boolean value.
def read_bit(self): """Read a single boolean value.""" if not self.bitcount: self.bits = ord(self.input.read(1)) self.bitcount = 8 result = (self.bits & 1) == 1 self.bits >>= 1 self.bitcount -= 1 return result
Read one byte, return as an integer
def read_octet(self): """Read one byte, return as an integer""" self.bitcount = self.bits = 0 return unpack('B', self.input.read(1))[0]
Read an unsigned 32-bit integer
def read_long(self): """Read an unsigned 32-bit integer""" self.bitcount = self.bits = 0 return unpack('>I', self.input.read(4))[0]
Read an unsigned 64-bit integer
def read_longlong(self): """Read an unsigned 64-bit integer""" self.bitcount = self.bits = 0 return unpack('>Q', self.input.read(8))[0]
Read float value.
def read_float(self): """Read float value.""" self.bitcount = self.bits = 0 return unpack('>d', self.input.read(8))[0]
Read an unsigned 16-bit integer
def read_short(self): """Read an unsigned 16-bit integer""" self.bitcount = self.bits = 0 return unpack('>H', self.input.read(2))[0]
Read a short string that's stored in up to 255 bytes. The encoding isn't specified in the AMQP spec, so assume it's utf-8
def read_shortstr(self): """Read a short string that's stored in up to 255 bytes. The encoding isn't specified in the AMQP spec, so assume it's utf-8 """ self.bitcount = self.bits = 0 slen = unpack('B', self.input.read(1))[0] return self.input.read(slen).decode(...
Read an AMQP table, and return as a Python dictionary.
def read_table(self): """Read an AMQP table, and return as a Python dictionary.""" self.bitcount = self.bits = 0 tlen = unpack('>I', self.input.read(4))[0] table_data = AMQPReader(self.input.read(tlen)) result = {} while table_data.input.tell() < tlen: name = ...
Write an integer as an unsigned 16-bit value.
def write_short(self, n): """Write an integer as an unsigned 16-bit value.""" if n < 0 or n > 65535: raise FrameSyntaxError( 'Octet {0!r} out of range 0..65535'.format(n)) self._flushbits() self.out.write(pack('>H', int(n)))
Write an integer as an unsigned2 32-bit value.
def write_long(self, n): """Write an integer as an unsigned2 32-bit value.""" if n < 0 or n >= 4294967296: raise FrameSyntaxError( 'Octet {0!r} out of range 0..2**31-1'.format(n)) self._flushbits() self.out.write(pack('>I', n))
Write a string up to 255 bytes long (after any encoding). If passed a unicode string, encode with UTF-8.
def write_shortstr(self, s): """Write a string up to 255 bytes long (after any encoding). If passed a unicode string, encode with UTF-8. """ self._flushbits() if isinstance(s, string): s = s.encode('utf-8') if len(s) > 255: raise FrameSyntaxError...
Write out a Python dictionary made of up string keys, and values that are strings, signed integers, Decimal, datetime.datetime, or sub-dictionaries following the same constraints.
def write_table(self, d): """Write out a Python dictionary made of up string keys, and values that are strings, signed integers, Decimal, datetime.datetime, or sub-dictionaries following the same constraints.""" self._flushbits() table_data = AMQPWriter() for k, v in item...
Write out a Python datetime.datetime object as a 64-bit integer representing seconds since the Unix epoch.
def write_timestamp(self, v): """Write out a Python datetime.datetime object as a 64-bit integer representing seconds since the Unix epoch.""" self.out.write(pack('>Q', long_t(calendar.timegm(v.utctimetuple()))))
Given the raw bytes containing the property-flags and property-list from a content-frame-header, parse and insert into a dictionary stored in this object as an attribute named 'properties'.
def _load_properties(self, raw_bytes): """Given the raw bytes containing the property-flags and property-list from a content-frame-header, parse and insert into a dictionary stored in this object as an attribute named 'properties'.""" r = AMQPReader(raw_bytes) # # Read 1...
serialize the 'properties' attribute (a dictionary) into the raw bytes making up a set of property flags and a property list, suitable for putting into a content frame header.
def _serialize_properties(self): """serialize the 'properties' attribute (a dictionary) into the raw bytes making up a set of property flags and a property list, suitable for putting into a content frame header.""" shift = 15 flag_bits = 0 flags = [] raw_bytes = A...
Create an executable script. Args: filepath (str): File to create. body (str or callable): Contents of the script. If a callable, its code is used as the script body. program (str): Name of program to launch the script, 'python' if None
def create_executable_script(filepath, body, program=None): """Create an executable script. Args: filepath (str): File to create. body (str or callable): Contents of the script. If a callable, its code is used as the script body. program (str): Name of program to launch the ...
Create a 'forwarding' script. A forwarding script is one that executes some arbitrary Rez function. This is used internally by Rez to dynamically create a script that uses Rez, even though the parent environment may not be configured to do so.
def create_forwarding_script(filepath, module, func_name, *nargs, **kwargs): """Create a 'forwarding' script. A forwarding script is one that executes some arbitrary Rez function. This is used internally by Rez to dynamically create a script that uses Rez, even though the parent environment may not be ...
Remove duplicates from a list while keeping order.
def dedup(seq): """Remove duplicates from a list while keeping order.""" seen = set() for item in seq: if item not in seen: seen.add(item) yield item
Given a list, find the last occurance of a sublist within it. Returns: Index where the sublist starts, or None if there is no match.
def find_last_sublist(list_, sublist): """Given a list, find the last occurance of a sublist within it. Returns: Index where the sublist starts, or None if there is no match. """ for i in reversed(range(len(list_) - len(sublist) + 1)): if list_[i] == sublist[0] and list_[i:i + len(subli...
Launch a help section.
def open(self, section_index=0): """Launch a help section.""" uri = self._sections[section_index][1] if len(uri.split()) == 1: self._open_url(uri) else: if self._verbose: print "running command: %s" % uri p = popen(uri, shell=True) ...
Print help sections.
def print_info(self, buf=None): """Print help sections.""" buf = buf or sys.stdout print >> buf, "Sections:" for i, section in enumerate(self._sections): print >> buf, " %s:\t%s (%s)" % (i + 1, section[0], section[1])
Set the pool of servers used by this client. @param servers: an array of servers. Servers can be passed in two forms: 1. Strings of the form C{"host:port"}, which implies a default weight of 1. 2. Tuples of the form C{("host:port", weight)}, where C{weight} is an int...
def set_servers(self, servers): """ Set the pool of servers used by this client. @param servers: an array of servers. Servers can be passed in two forms: 1. Strings of the form C{"host:port"}, which implies a default weight of 1. 2. Tuples of the form C{("host:po...
Get statistics from each of the servers. @param stat_args: Additional arguments to pass to the memcache "stats" command. @return: A list of tuples ( server_identifier, stats_dictionary ). The dictionary contains a number of name/value pairs specifying the name of th...
def get_stats(self, stat_args = None): '''Get statistics from each of the servers. @param stat_args: Additional arguments to pass to the memcache "stats" command. @return: A list of tuples ( server_identifier, stats_dictionary ). The dictionary contains a number of name...
Delete multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 >>> mc.delete_multi(['key1', 'key2']) 1 >>> mc.get_multi(['key1', 'key...
def delete_multi(self, keys, time=0, key_prefix=''): ''' Delete multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 >>> mc.delete...
Deletes a key from the memcache. @return: Nonzero on success. @param time: number of seconds any subsequent set / update commands should fail. Defaults to None for no delay. @rtype: int
def delete(self, key, time=0): '''Deletes a key from the memcache. @return: Nonzero on success. @param time: number of seconds any subsequent set / update commands should fail. Defaults to None for no delay. @rtype: int ''' if self.do_check_key: self....
Add new key with value. Like L{set}, but only stores in memcache if the key doesn't already exist. @return: Nonzero on success. @rtype: int
def add(self, key, val, time = 0, min_compress_len = 0): ''' Add new key with value. Like L{set}, but only stores in memcache if the key doesn't already exist. @return: Nonzero on success. @rtype: int ''' return self._set("add", key, val, time, min_compress_len)
Append the value to the end of the existing key's value. Only stores in memcache if key already exists. Also see L{prepend}. @return: Nonzero on success. @rtype: int
def append(self, key, val, time=0, min_compress_len=0): '''Append the value to the end of the existing key's value. Only stores in memcache if key already exists. Also see L{prepend}. @return: Nonzero on success. @rtype: int ''' return self._set("append", key, v...
Prepend the value to the beginning of the existing key's value. Only stores in memcache if key already exists. Also see L{append}. @return: Nonzero on success. @rtype: int
def prepend(self, key, val, time=0, min_compress_len=0): '''Prepend the value to the beginning of the existing key's value. Only stores in memcache if key already exists. Also see L{append}. @return: Nonzero on success. @rtype: int ''' return self._set("prepend"...
Replace existing key with value. Like L{set}, but only stores in memcache if the key already exists. The opposite of L{add}. @return: Nonzero on success. @rtype: int
def replace(self, key, val, time=0, min_compress_len=0): '''Replace existing key with value. Like L{set}, but only stores in memcache if the key already exists. The opposite of L{add}. @return: Nonzero on success. @rtype: int ''' return self._set("replace", key,...
Unconditionally sets a key to a given value in the memcache. The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all o...
def set(self, key, val, time=0, min_compress_len=0): '''Unconditionally sets a key to a given value in the memcache. The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate ...
Sets a key to a given value in the memcache if it hasn't been altered since last fetched. (See L{gets}). The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value...
def cas(self, key, val, time=0, min_compress_len=0): '''Sets a key to a given value in the memcache if it hasn't been altered since last fetched. (See L{gets}). The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. ...
Compute the mapping of server (_Host instance) -> list of keys to stuff onto that server, as well as the mapping of prefixed key -> original key.
def _map_and_prefix_keys(self, key_iterable, key_prefix): """Compute the mapping of server (_Host instance) -> list of keys to stuff onto that server, as well as the mapping of prefixed key -> original key. """ # Check it just once ... key_extra_len=len(key_prefix) if k...
Sets multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 This method is recommended over regular L{set} as it lowers the number of tota...
def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0): ''' Sets multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'} 1 ...
Transform val to a storable representation, returning a tuple of the flags, the length of the new value, and the new value itself.
def _val_to_store_info(self, val, min_compress_len): """ Transform val to a storable representation, returning a tuple of the flags, the length of the new value, and the new value itself. """ flags = 0 if isinstance(val, str): pass elif isinstance(val, int)...
Retrieves multiple keys from the memcache doing just one query. >>> success = mc.set("foo", "bar") >>> success = mc.set("baz", 42) >>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42} 1 >>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == [] 1 ...
def get_multi(self, keys, key_prefix=''): ''' Retrieves multiple keys from the memcache doing just one query. >>> success = mc.set("foo", "bar") >>> success = mc.set("baz", 42) >>> mc.get_multi(["foo", "baz", "foobar"]) == {"foo": "bar", "baz": 42} 1 >>> mc.set_m...
Checks sanity of key. Fails if: Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength). Contains control characters (Raises MemcachedKeyCharacterError). Is not a string (Raises MemcachedStringEncodingError) Is an unicode string (Raises MemcachedStringEncoding...
def check_key(self, key, key_extra_len=0): """Checks sanity of key. Fails if: Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength). Contains control characters (Raises MemcachedKeyCharacterError). Is not a string (Raises MemcachedStringEncodingError) ...
Read a line and return it. If "raise_exception" is set, raise _ConnectionDeadError if the read fails, otherwise return an empty string.
def readline(self, raise_exception=False): """Read a line and return it. If "raise_exception" is set, raise _ConnectionDeadError if the read fails, otherwise return an empty string. """ buf = self.buffer if self.socket: recv = self.socket.recv else: ...