zensols.util package¶
Submodules¶
zensols.util.clip module¶
Provides access to the system clipboard. Currently only macOS is supported.
zensols.util.executor module¶
Simplifies external process handling.
- class zensols.util.executor.ExecutableFinder(path_var=None, raise_on_missing=True)[source]¶
Bases:
objectSearches for an executable binary in the search path. The default search path (
path_var) is set to the operating system’sPATHenvironment variable.- __init__(path_var=None, raise_on_missing=True)¶
- find(name)[source]¶
Like
find_all(), but returns only the first found executable.
- class zensols.util.executor.Executor(logger, dry_run=False, check_exit_value=0, timeout=None, async_proc=False, working_dir=None)[source]¶
Bases:
objectRun a process and log output. The process is run in the foreground by default, or background. If the later, a process object is returned from
run().- __init__(logger, dry_run=False, check_exit_value=0, timeout=None, async_proc=False, working_dir=None)¶
-
check_exit_value:
int= 0¶ Compare and raise an exception if the exit value of the process is not this number, or
Noneto not check.
zensols.util.fail module¶
General utility classes to measuring time it takes to do work, to logging and fork/exec operations.
- exception zensols.util.fail.APIError[source]¶
Bases:
ExceptionBase exception from which almost all library raised errors extend.
- __annotations__ = {}¶
- __module__ = 'zensols.util.fail'¶
- __weakref__¶
list of weak references to the object
- class zensols.util.fail.Failure(exception=None, thrower=None, traceback=None, message=None)[source]¶
Bases:
WritableContains information for failures as caught exceptions used by programatic methods.
- __init__(exception=None, thrower=None, traceback=None, message=None)¶
- print_stack(writer=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Print the stack trace of the exception that caused the failure.
- property traceback_str: str¶
The stack trace as a string.
:see
print_stack()
- write(depth=0, writer=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Write the contents of this instance to
writerusing indentiondepth.- Parameters:
depth (
int) – the starting indentation depthwriter (
TextIOBase) – the writer to dump the content of this writable
zensols.util.hasher module¶
Utilities for hashing text.
- class zensols.util.hasher.Hasher(short=True, decode='hex')[source]¶
Bases:
objectA utility class that creates hexadecimal hash values for text.
- See:
- __init__(short=True, decode='hex')¶
zensols.util.log module¶
Utility classes and context managers around logging.
- class zensols.util.log.LogConfigurer(logger=<RootLogger root (WARNING)>, log_format='%(asctime)s %(levelname)s %(message)s', level=None)[source]¶
Bases:
objectConfigure logging to go to a file or Graylog.
- class zensols.util.log.LoggerStream(logger, log_level=20)[source]¶
Bases:
objectEach line of standard out/error becomes a logged line
- class zensols.util.log.StreamLogDumper(stream, logger, level)[source]¶
Bases:
ThreadRedirect stream output to a logger in a running thread.
- __init__(stream, logger, level)[source]¶
This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
args is a list or tuple of arguments for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.
- run()[source]¶
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
- zensols.util.log.add_logging_level(level_name, level_num, method_name=None)[source]¶
Comprehensively adds a new logging level to the logging module and the currently configured logging class.
level_name becomes an attribute of the logging module with the value level_num. method_name becomes a convenience method for both logging itself and the class returned by logging.getLoggerClass() (usually just logging.Logger). If method_name is not specified, level_name.lower() is used.
To avoid accidental clobberings of existing attributes, this method will raise an AttributeError if the level name is already an attribute of the logging module or if the method name is already present.
See `Stack Overflow`_ for attribution.
- class zensols.util.log.loglevel(name='', level=10, init=None, enable=True)[source]¶
Bases:
objectObject used with a
withscope that sets the logging level temporarily and sets it back.Example:
with loglevel(__name__): logger.debug('test') with loglevel(['zensols.persist', 'zensols.config'], init=True): logger.debug('test')
- __init__(name='', level=10, init=None, enable=True)[source]¶
Configure the temporary logging setup.
- Parameters:
name (
Union[List[str],str,None]) – the name of the logger to set, or if a list is passed, configure all loggers in the list; if a string, configure all logger names split on spaces; ifNoneorFalse, do not configure anything (handy for REPL prototyping); default to the root logger to log everythinglevel (
int) – the logging level, which defaults tologging.DEBUGinit (
Union[bool,int]) – if notNone, initialize logging withlogging.basicConfig()using the given level orTrueto uselogging.WARNINGenable (
bool) – ifFalse, disable any logging configuration changes for the block
zensols.util.package module¶
A convenience class around the pkg_resources module.
- exception zensols.util.package.PackageError[source]¶
Bases:
APIErrorRaised for errors related to packages from this module.
- __annotations__ = {}¶
- __module__ = 'zensols.util.package'¶
- class zensols.util.package.PackageManager(pip_install_args=('--use-deprecated=legacy-resolver',), no_deps=False, force=False)[source]¶
Bases:
objectGather and parse requirements and optionally install them.
- __init__(pip_install_args=('--use-deprecated=legacy-resolver',), no_deps=False, force=False)¶
- find_requirements(sources)[source]¶
The requirements contained in this manager. .
-
force:
bool= False¶ Whether to force installs and uninstalls regardless of whether a dependency is already (un)installed. This has no effect on the pip install command (
--force).
- get_installed_requirement(package)[source]¶
Get an already installed requirement by name.
- Parameters:
package (
str) – the package name (i.e.zensols.util)- Return type:
- get_requirement(package)[source]¶
First try to get an installed (
get_installed_requirement), and if not found, back off to finding one with :class:().PackageResource`.- Parameters:
package (
str) – the package name (i.e.zensols.util)- Return type:
- install(requirement)[source]¶
Install a package in this Python enviornment with pip.
- Parameters:
requirement (
PackageRequirement) – the requirement to installno_deps – if
Truedo not install the package’s dependencies
- Return type:
- Returns:
the output from the pip command invocation
-
pip_install_args:
Tuple[str,...] = ('--use-deprecated=legacy-resolver',)¶ Additional argument used for installing packages with
pip.
- uninstall(requirement)[source]¶
Uninstall a package in this Python enviornment with pip.
- Parameters:
requirement (
PackageRequirement) – the requirement to uninstallno_deps – if
Truedo not install the package’s dependencies
- Return type:
- Returns:
the output from the pip command invocation
- class zensols.util.package.PackageRequirement(requirement, source=None, meta=None)[source]¶
Bases:
WritableA Python requirement specification.
- __init__(requirement, source=None, meta=None)¶
-
meta:
Dict[str,str] = None¶ The metadata of the package. This is populated by
PackageManager.get_installed_requirement().
-
requirement:
Requirement¶ The requirement of the package.
- property specifier: SpecifierSet¶
- class zensols.util.package.PackageResource(name)[source]¶
Bases:
WritableContains resources of installed Python packages. It makes the
distributionavailable and provides access to to resource files withget_path()and as an index.- __init__(name)¶
- get_path(resource)[source]¶
Return a resource file name by name. Optionally return resource as a relative path if the package does not exist.
zensols.util.sci module¶
Scientific utilities.
- class zensols.util.sci.ScientificUtil[source]¶
Bases:
objectA class containing utility methods.
- static fixed_format(v, length=1, add_pad=False)[source]¶
Format a number to a width resorting to scientific notation where necessary. The returned string is left padded with space in cases where scientific notation is too wide for
v > 0. The mantissa is cut off also forv > 0when the string version of the number is too wide.
zensols.util.std module¶
Utility classes for system based functionality.
- class zensols.util.std.FileLikeType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Bases:
EnumIndicates readability aspects of a Python object. Enumeration values and helper methods specify how an object might be readable and in what way. This class describes types can be files-like,
pathlib.Path, strings that point to files, andsys.stdin. The string or pathSTANDARD_OUT_PATHis treated as standard in.- filelike = 1¶
- classmethod from_instance(instance)[source]¶
Return an instance of this enumeration based on the type of
instance.- Return type:
- property is_openable: bool¶
Whether an object can be opened with :function:`open`.
- static is_standard_in(instance)[source]¶
Whether
instanceis notsys.stdinbut represents it.- Return type:
- none = 5¶
- path = 2¶
- stdin = 4¶
- string_path = 3¶
- class zensols.util.std.openread(source, interpret_str=False, raise_error=True, no_close=False, *open_args, **open_kwargs)[source]¶
Bases:
objectOpen an file object for reading if possible, and close it only if necessary. Input types are described by
FileLikeType. If the source isExample:
import sys import itertools as it with openread(sys.stdin) as f: line = it.islice(f.readlines(), 1)
- __init__(source, interpret_str=False, raise_error=True, no_close=False, *open_args, **open_kwargs)[source]¶
Initialize.
- Parameters:
source (
Any) – the data sourceinterpret_str (
bool) – whether to read the string or use it as a file nameraise_error (
bool) – ifTrueraiseOSErrorifsourceis an object that can not be opened or readno_close (
bool) – do not close the file object (if opened in the first place), even if it should beopen_kwargs – keyword argument passed to
open()
- class zensols.util.std.stdout(path=None, extension=None, recommend_name='unnamed', capture=False, logger=<Logger zensols.util.std (WARNING)>, open_args='w')[source]¶
Bases:
objectWrite to a file or standard out. This is desigend to be used in command line application (CLI) applications with the
zensols.climodule. Application class can pass apathlib.Pathto a method with this class.Example:
def write(self, output_file: Path = Path('-')): """Write data. :param output_file: the output file name, ``-`` for standard out, or ``+`` for a default """ with stdout(output_file, recommend_name='unknown-file-name', extension='txt', capture=True, logger=logger): print('write data')
- __init__(path=None, extension=None, recommend_name='unnamed', capture=False, logger=<Logger zensols.util.std (WARNING)>, open_args='w')[source]¶
Initailize where to write. If the path is
Noneor its name isSTANDARD_OUT_PATH, then standard out is used instead of opening a file. Ifpathis set toFILE_RECOMMEND_NAME, it is constructed fromrecommend_name. If no suffix (file extension) is provided forpaththenextesionis used if given.- Parameters:
extension (
str) – the extension (sans leading dot.) to postpend to the path if one is not provied in the file namerecommend_name (
str) – the name to use as the prefix ifpathis not providedcapture (
bool) – whether to redirect standard out (sys.stdout) to the file provided bypathif not already indicated to be standard outlogger (
Logger) – used to log the successful output of the file, which defaults to this module’s loggeropen_args (
str) – the arguments given toopen(), which defaults towif none are given
- class zensols.util.std.stdwrite(stdout=None, stderr=None)[source]¶
Bases:
objectCapture standard out/error.
- __init__(stdout=None, stderr=None)[source]¶
Initialize.
- Parameters:
stdout (
TextIOBase) – the data sink for stdout (i.e.io.StringIO)stdout – the data sink for stderr
zensols.util.tempfile module¶
Classes to generate, track and clean up temporary files.
- class zensols.util.tempfile.TemporaryFileName(directory=None, file_fmt='{name}', create=False, remove=True)[source]¶
Bases:
objectCreate a temporary file names on the file system. Note that this does not create the file object itself, only the file names. In addition, the generated file names are tracked and allow for deletion. Specified directories are also created, which is only needed for non-system temporary directories.
The object is iterable, so usage with
itertools.islicecan be used to get as many temporary file names as desired. Calling instances (no arguments) generate a single file name.- __init__(directory=None, file_fmt='{name}', create=False, remove=True)[source]¶
Initialize with file system data.
- Parameters:
directory (
str) – the parent directory of the generated filefile_fmt (
str) – a file format that substitutesnamefor the create temporary file name; defaults to{name}create (
bool) – ifTrue, createdirectoryif it doesn’t existremove (
bool) – ifTrue, remove tracked generated file names if they exist
- See tempfile:
- class zensols.util.tempfile.tempfile(*args, **kwargs)[source]¶
Bases:
objectGenerate a temporary file name and return the name in the
withstatement. Arguments to the form are the same asTemporaryFileName. The temporary file is deleted after completion (seeTemporaryFileName).Example:
with tempfile('./tmp', create=True) as fname: print(f'writing to {fname}') with open(fname, 'w') as f: f.write('this file will be deleted, but left with ./tmp\n')
zensols.util.time module¶
Peformance measure convenience utils.
- class zensols.util.time.DurationFormatter(duration)[source]¶
Bases:
objectUtility class to format time as duration.
- exception zensols.util.time.TimeoutError[source]¶
Bases:
ExceptionRaised when a time out even occurs in
timeout()ortimeprotect.- __module__ = 'zensols.util.time'¶
- __weakref__¶
list of weak references to the object
- class zensols.util.time.time(msg='finished', level=20, logger=None)[source]¶
Bases:
objectUsed in a
withscope that executes the body and logs the elapsed time.Format f-strings are supported as the locals are taken from the calling frame on exit. This means you can do things like:
with time('processed {cnt} items'): cnt = 5 tm.sleep(1)
which produeces:
processed 5 items.See the initializer documentation about special treatment for global loggers.
- __init__(msg='finished', level=20, logger=None)[source]¶
Create the time object.
If a logger is not given, it is taken from the calling frame’s global variable named
logger. If this global doesn’t exit it logs to standard out. Otherwise, standard out/error can be used if givensys.stdoutorsys.stderr.- Parameters:
msg (
str) – the message log when exiting the closurelogger (
Union[Logger,TextIOBase]) – the logger to use for logging or a file like object (i.e.sys.stdout) as a data synclevel – the level at which the message is logged
- zensols.util.time.timeout(seconds=10, error_message='STREAM ioctl timeout')[source]¶
This creates a decorator called @timeout that can be applied to any long running functions.
So, in your application code, you can use the decorator like so:
from timeout import timeout # Timeout a long running function with the default expiry of # TIMEOUT_DEFAULT seconds. @timeout def long_running_function1(): pass
This was derived from the David Narayan’s `StackOverflow`_ thread.
- class zensols.util.time.timeprotect(seconds=10, timeout_handler=None, context=None, error_message='STREAM ioctl timeout')[source]¶
Bases:
objectInvokes a block and bails if not completed in a specified number of seconds.
- Parameters:
seconds – the number of seconds to wait
timeout_handler – function that takes a single argument, which is this
timeprotectobject instance; ifNone, then nothing is done if the block times outcontext – an object accessible from the
timeout_handerviaself, which defaults toNone
- See:
zensols.util.warn module¶
Utilities to silence warnings.
- class zensols.util.warn.WarningSilencer(filters)[source]¶
Bases:
objectA utility class to invoke the Python
warningssystem to suppress (ignore) warnings. Both the category (warning class) and a regular expression can be provided.- __init__(filters)¶
- property filter_parameters: Tuple[Dict[str, Any], ...]¶
A list of dictionaries, each of which are used as keyword parameters to :function:`warning.filterwarnings`.
-
filters:
Tuple[Dict[str,str],...]¶ A tuple of dictionaries that will be given to the :function:`warning.filterwarnings` function. This is meant to be added to an application configuration.
For example, in a Zensols YAML configuration:
warn_silencer: class_name: zensols.util.warn.WarningSilencer filters: - action: 'ignore' category: FutureWarning message: '^Some error message.*'
zensols.util.writable module¶
A class that allows human readable information (sometimes debugging) output with a hierarchical structure.
- class zensols.util.writable.Writable[source]¶
Bases:
objectAn interface for classes that have multi-line debuging capability.
- _write(c)[source]¶
Use
WritableContextas a data sink.
- _set_indent(indent=None)[source]¶
Set the indentation for the instance. By default, this value is 4.
- Parameters:
indent (
int) – the value to set as the indent for this instance, orNoneto unset it
- _write_line(line, depth, writer, max_len=False, repl_newlines=False)[source]¶
Write a line of text
linewith the correct indentation perdepthtowriter.- Parameters:
max_line – truncate to the given length if an
intorWRITABLE_MAX_COLifTrue- Repl_newlines:
whether to replace newlines with spaces
- _write_block(lines, depth, writer, limit=None)[source]¶
Write a block of text with indentation.
- Parameters:
limit (
int) – the max number of lines in the block to write
- _write_wrap(text, depth, writer, width=None, **kwargs)[source]¶
Like
_write_line()but wrap text perwidth.- Parameters:
text (
str) – the text to word wrapdepth (
int) – the starting indentation depthwriter (
TextIOBase) – the writer to dump the content of this writablewidth (
int) – the width of the text before wrapping, which defaults toWRITABLE_MAX_COLkwargs – the keyword arguments given to
textwarp.wrap()
- _write_iterable(data, depth, writer, include_index=None)[source]¶
Write list
datawith the correct indentation perdepthtowriter.- Parameters:
include_index (
bool) – ifTrue, add an incrementing index for each element in the output
- _write_dict(data, depth, writer, inline=False, one_line=False)[source]¶
Write dictionary
datawith the correct indentation perdepthtowriter.
-
WRITABLE_INCLUDE_INDEX:
ClassVar[bool] = False¶ Whether to include index numbers with levels in sequences.
- write(depth=0, writer=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]¶
Write the contents of this instance to
writerusing indentiondepth.- Parameters:
depth (
int) – the starting indentation depthwriter (
TextIOBase) – the writer to dump the content of this writable