INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns an existing or creates and returns a new counter: param name: name of the counter: return: the counter object
def counter(self, name): """ Returns an existing or creates and returns a new counter :param name: name of the counter :return: the counter object """ with self._lock: if name not in self._counters: if self._registry._ignore_patterns and any( ...
Returns an existing or creates and returns a new gauge: param name: name of the gauge: return: the gauge object
def gauge(self, name): """ Returns an existing or creates and returns a new gauge :param name: name of the gauge :return: the gauge object """ with self._lock: if name not in self._gauges: if self._registry._ignore_patterns and any( ...
Collects all metrics attached to this metricset and returns it as a list together with a timestamp in microsecond precision.
def collect(self): """ Collects all metrics attached to this metricset, and returns it as a list, together with a timestamp in microsecond precision. The format of the return value should be { "samples": {"metric.name": {"value": some_float}, ...}, ...
Tags current transaction. Both key and value of the tag should be strings.
def tag(**tags): """ Tags current transaction. Both key and value of the tag should be strings. """ transaction = execution_context.get_transaction() if not transaction: error_logger.warning("Ignored tags %s. No transaction currently active.", ", ".join(tags.keys())) else: transa...
Begin a new span: param name: name of the span: param span_type: type of the span: param context: a context dict: param leaf: True if this is a leaf span: param tags: a flat string/ string dict of tags: return: the Span object
def begin_span(self, name, span_type, context=None, leaf=False, tags=None): """ Begin a new span :param name: name of the span :param span_type: type of the span :param context: a context dict :param leaf: True if this is a leaf span :param tags: a flat string/str...
If current trace_parent has no span_id generate one then return it
def ensure_parent_id(self): """If current trace_parent has no span_id, generate one, then return it This is used to generate a span ID which the RUM agent will use to correlate the RUM transaction with the backend transaction. """ if self.trace_parent.span_id == self.id: ...
Tag this transaction with one or multiple key/ value tags. Both the values should be strings
def tag(self, **tags): """ Tag this transaction with one or multiple key/value tags. Both the values should be strings transaction_obj.tag(key1="value1", key2="value2") Note that keys will be dedotted, replacing dot (.), star (*) and double quote (") with an underscore (_) ...
Start a new transactions and bind it in a thread - local variable
def begin_transaction(self, transaction_type, trace_parent=None): """ Start a new transactions and bind it in a thread-local variable :returns the Transaction object """ if trace_parent: is_sampled = bool(trace_parent.trace_options.recorded) else: ...
Check your settings for common misconfigurations
def handle_check(self, command, **options): """Check your settings for common misconfigurations""" passed = True client = DjangoClient(metrics_interval="0ms") def is_set(x): return x and x != "None" # check if org/app is set: if is_set(client.config.service_...
wrapper around self. stdout/ stderr to ensure Django 1. 4 compatibility
def write(self, msg, style_func=None, ending=None, stream=None): """ wrapper around self.stdout/stderr to ensure Django 1.4 compatibility """ if stream is None: stream = self.stdout if OutputWrapper is None: ending = "\n" if ending is None else ending ...
Called when an exception has been raised in the code run by ZeroRPC
def server_inspect_exception(self, req_event, rep_event, task_ctx, exc_info): """Called when an exception has been raised in the code run by ZeroRPC""" # Hide the zerorpc internal frames for readability, for a REQ/REP or # REQ/STREAM server the frames to hide are: # - core.ServerBase._a...
Method called for unsampled wrapped calls. This can e. g. be used to add traceparent headers to the underlying http call for HTTP instrumentations.
def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): """ Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the underlying http call for HTTP instrumentations. :param module: :param method...
Auto - instruments code to get nice spans
def instrument(client): """ Auto-instruments code to get nice spans """ from elasticapm.instrumentation.control import instrument instrument() try: import celery # noqa F401 from elasticapm.contrib.celery import register_instrumentation register_instrumentation(client)...
Configures logging to pipe to Elastic APM.
def setup_logging(handler, exclude=("gunicorn", "south", "elasticapm.errors")): """ Configures logging to pipe to Elastic APM. - ``exclude`` is a list of loggers that shouldn't go to ElasticAPM. For a typical Python install: >>> from elasticapm.handlers.logging import LoggingHandler >>> clien...
Given an ElasticAPM client and an RQ worker registers exception handlers with the worker so exceptions are logged to the apm server.
def register_elasticapm(client, worker): """Given an ElasticAPM client and an RQ worker, registers exception handlers with the worker so exceptions are logged to the apm server. E.g.: from elasticapm.contrib.django.models import client from elasticapm.contrib.rq import register_elasticapm wor...
Get the transaction registered for the current thread.
def get_transaction(self, clear=False): """ Get the transaction registered for the current thread. :return: :rtype: Transaction """ transaction = getattr(self.thread_local, "transaction", None) if clear: self.thread_local.transaction = None re...
Returns context_lines before and after lineno from file. Returns ( pre_context_lineno pre_context context_line post_context ).
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ lineno = lineno - 1 lower_bound = max(0, lineno - context_lines) up...
Given a traceback object it will iterate over all frames that do not contain the __traceback_hide__ local variable.
def iter_traceback_frames(tb): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ while tb: # support for __traceback_hide__ which is used by a few libraries # to hide internal frames. frame = t...
Given an optional list of frames ( defaults to current stack ) iterates over all frames that do not contain the __traceback_hide__ local variable.
def iter_stack_frames(frames=None, start_frame=None, skip=0, skip_top_modules=()): """ Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. Frames can be skipped by either providing a number, or a tuple...
Given a list of frames returns a list of stack information dictionary objects that are JSON - ready.
def get_stack_info( frames, with_locals=True, library_frame_context_lines=None, in_app_frame_context_lines=None, include_paths_re=None, exclude_paths_re=None, locals_processor_func=None, ): """ Given a list of frames, returns a list of stack information dictionary objects that ar...
Uses either uwsgi s atexit mechanism or atexit from the stdlib.
def atexit_register(func): """ Uses either uwsgi's atexit mechanism, or atexit from the stdlib. When running under uwsgi, using their atexit handler is more reliable, especially when using gevent :param func: the function to call at exit """ try: import uwsgi orig = getattr...
Returns library paths depending on the used platform.
def get_default_library_patters(): """ Returns library paths depending on the used platform. :return: a list of glob paths """ python_version = platform.python_version_tuple() python_implementation = platform.python_implementation() system = platform.system() if python_implementation ==...
Turns a werkzeug. MultiDict or django. MultiValueDict into a dict with list values: param d: a MultiDict or MultiValueDict instance: return: a dict instance
def multidict_to_dict(d): """ Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with list values :param d: a MultiDict or MultiValueDict instance :return: a dict instance """ return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))
Returns True if the given request * shouldn t * notify the site managers.
def _is_ignorable_404(uri): """ Returns True if the given request *shouldn't* notify the site managers. """ urls = getattr(django_settings, "IGNORABLE_404_URLS", ()) return any(pattern.search(uri) for pattern in urls)
Reads docker/ kubernetes metadata ( container id pod id ) from/ proc/ self/ cgroup
def get_cgroup_container_metadata(): """ Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup The result is a nested dictionary with the detected IDs, e.g. { "container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"}, "...
Reads lines from a file handle and tries to parse docker container IDs and kubernetes Pod IDs.
def parse_cgroups(filehandle): """ Reads lines from a file handle and tries to parse docker container IDs and kubernetes Pod IDs. See tests.utils.docker_tests.test_cgroup_parsing for a set of test cases :param filehandle: :return: nested dictionary or None """ for line in filehandle: ...
: param events: list of event types
def for_events(*events): """ :param events: list of event types Only calls wrapped function if given event_type is in list of events """ events = set(events) def wrap(func): func.event_types = events return func return wrap
Removes local variables from any frames.
def remove_stacktrace_locals(client, event): """ Removes local variables from any frames. :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ func = lambda frame: frame.pop("vars", None) return _process_stack_frames(event, func)
Sanitizes local variables in all frames
def sanitize_stacktrace_locals(client, event): """ Sanitizes local variables in all frames :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ def func(frame): if "vars" in frame: frame["vars"] = varmap(_sanitiz...
Sanitizes http request cookies
def sanitize_http_request_cookies(client, event): """ Sanitizes http request cookies :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ # sanitize request.cookies dict try: cookies = event["context"]["request"]["cookie...
Sanitizes the set - cookie header of the response: param client: an ElasticAPM client: param event: a transaction or error event: return: The modified event
def sanitize_http_response_cookies(client, event): """ Sanitizes the set-cookie header of the response :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ try: cookie_string = event["context"]["response"]["headers"]["set-cook...
Sanitizes http request/ response headers
def sanitize_http_headers(client, event): """ Sanitizes http request/response headers :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ # request headers try: headers = event["context"]["request"]["headers"] ev...
Sanitizes WSGI environment variables
def sanitize_http_wsgi_env(client, event): """ Sanitizes WSGI environment variables :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ try: env = event["context"]["request"]["env"] event["context"]["request"]["env"]...
Sanitizes http request query string
def sanitize_http_request_querystring(client, event): """ Sanitizes http request query string :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ try: query_string = force_text(event["context"]["request"]["url"]["search"], e...
Sanitizes http request body. This only works if the request body is a query - encoded string. Other types ( e. g. JSON ) are not handled by this sanitizer.
def sanitize_http_request_body(client, event): """ Sanitizes http request body. This only works if the request body is a query-encoded string. Other types (e.g. JSON) are not handled by this sanitizer. :param client: an ElasticAPM client :param event: a transaction or error event :return: T...
sanitizes a string that contains multiple key/ value items: param unsanitized: the unsanitized string: param itemsep: string that separates items: param kvsep: string that separates key from value: return: a sanitized string
def _sanitize_string(unsanitized, itemsep, kvsep): """ sanitizes a string that contains multiple key/value items :param unsanitized: the unsanitized string :param itemsep: string that separates items :param kvsep: string that separates key from value :return: a sanitized string """ sanit...
Captures and processes an event and pipes it off to Client. send.
def capture(self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs): """ Captures and processes an event and pipes it off to Client.send. """ if event_type == "Exception": # never gather log stack for exceptions stack = False ...
Creates an event from message.
def capture_message(self, message=None, param_message=None, **kwargs): """ Creates an event from ``message``. >>> client.capture_message('My event just happened!') """ return self.capture("Message", message=message, param_message=param_message, **kwargs)
Creates an event from an exception.
def capture_exception(self, exc_info=None, handled=True, **kwargs): """ Creates an event from an exception. >>> try: >>> exc_info = sys.exc_info() >>> client.capture_exception(exc_info) >>> finally: >>> del exc_info If exc_info is not provide...
Register the start of a transaction on the client
def begin_transaction(self, transaction_type, trace_parent=None): """Register the start of a transaction on the client """ return self.tracer.begin_transaction(transaction_type, trace_parent=trace_parent)
Captures processes and serializes an event into a dict object
def _build_msg_for_logging( self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs ): """ Captures, processes and serializes an event into a dict object """ transaction = execution_context.get_transaction() if transaction: ...
Overrideable in derived clients to add frames/ info e. g. templates
def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """Overrideable in derived clients to add frames/info, e.g. templates""" return stacks.get_...
This utility executes a single notebook on a container.
def papermill( notebook_path, output_path, parameters, parameters_raw, parameters_file, parameters_yaml, parameters_base64, inject_input_path, inject_output_path, inject_paths, engine, prepare_only, kernel, cwd, progress_bar, log_output, log_level, ...
Wrapper to catch nb keyword arguments
def catch_nb_assignment(func): """ Wrapper to catch `nb` keyword arguments This helps catch `nb` keyword arguments and assign onto self when passed to the wrapped function. Used for callback methods when the caller may optionally have a new copy of the originally wrapped `nb` object. """ ...
Register entrypoints for an engine
def register_entry_points(self): """Register entrypoints for an engine Load handlers provided by other packages """ for entrypoint in entrypoints.get_group_all("papermill.engine"): self.register(entrypoint.name, entrypoint.load())
Retrieves an engine by name.
def get_engine(self, name=None): """Retrieves an engine by name.""" engine = self._engines.get(name) if not engine: raise PapermillException("No engine named '{}' found".format(name)) return engine
Fetch a named engine and execute the nb object against it.
def execute_notebook_with_engine(self, engine_name, nb, kernel_name, **kwargs): """Fetch a named engine and execute the nb object against it.""" return self.get_engine(engine_name).execute_notebook(nb, kernel_name, **kwargs)
Saves the wrapped notebook state.
def save(self, **kwargs): """ Saves the wrapped notebook state. If an output path is known, this triggers a save of the wrapped notebook state to the provided path. Can be used outside of cell state changes if execution is taking a long time to conclude but the notebook...
Initialize a notebook clearing its metadata and save it.
def notebook_start(self, **kwargs): """ Initialize a notebook, clearing its metadata, and save it. When starting a notebook, this initializes and clears the metadata for the notebook and its cells, and saves the notebook to the given output path. Called by Engine when e...
Set and save a cell s start state.
def cell_start(self, cell, cell_index=None, **kwargs): """ Set and save a cell's start state. Optionally called by engines during execution to initialize the metadata for a cell and save the notebook to the output path. """ if self.log_output: ceel_num = cell...
Set metadata when an exception is raised.
def cell_exception(self, cell, cell_index=None, **kwargs): """ Set metadata when an exception is raised. Called by engines when an exception is raised within a notebook to set the metadata on the notebook indicating the location of the failure. """ cell.metadata....
Finalize metadata for a cell and save notebook.
def cell_complete(self, cell, cell_index=None, **kwargs): """ Finalize metadata for a cell and save notebook. Optionally called by engines during execution to finalize the metadata for a cell and save the notebook to the output path. """ end_time = self.now() if...
Finalize the metadata for a notebook and save the notebook to the output path.
def notebook_complete(self, **kwargs): """ Finalize the metadata for a notebook and save the notebook to the output path. Called by Engine when execution concludes, regardless of exceptions. """ self.end_time = self.now() self.nb.metadata.papermill['end_time'] = ...
Refresh progress bar
def complete_pbar(self): """Refresh progress bar""" if hasattr(self, 'pbar') and self.pbar: self.pbar.n = len(self.nb.cells) self.pbar.refresh()
Clean up a progress bar
def cleanup_pbar(self): """Clean up a progress bar""" if hasattr(self, 'pbar') and self.pbar: self.pbar.close() self.pbar = None
A wrapper to handle notebook execution tasks.
def execute_notebook( cls, nb, kernel_name, output_path=None, progress_bar=True, log_output=False, **kwargs ): """ A wrapper to handle notebook execution tasks. Wraps the notebook object in a `NotebookExecutionManager` in order to track execution state in a uniform manner. T...
Performs the actual execution of the parameterized notebook locally.
def execute_managed_notebook( cls, nb_man, kernel_name, log_output=False, start_timeout=60, execution_timeout=None, **kwargs ): """ Performs the actual execution of the parameterized notebook locally. Args: nb (NotebookNode...
see: https:// docs. microsoft. com/ en - us/ azure/ storage/ common/ storage - dotnet - shared - access - signature - part - 1 # noqa: E501 abs:// myaccount. blob. core. windows. net/ sascontainer/ sasblob. txt?sastoken
def _split_url(self, url): """ see: https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1 # noqa: E501 abs://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sastoken """ match = re.match(r"abs://(.*)\.blob\.core\.windows\.ne...
Read storage at a given url
def read(self, url): """Read storage at a given url""" params = self._split_url(url) output_stream = io.BytesIO() block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ) block_blob_service.get_blob_to_str...
Returns a list of the files under the specified path
def listdir(self, url): """Returns a list of the files under the specified path""" params = self._split_url(url) block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ) blobs = block_blob_service.list_blobs(param...
Write buffer to storage at a given url
def write(self, buf, url): """Write buffer to storage at a given url""" params = self._split_url(url) block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ) block_blob_service.create_blob_from_text( ...
Executes a single notebook locally.
def execute_notebook( input_path, output_path, parameters=None, engine_name=None, prepare_only=False, kernel_name=None, progress_bar=True, log_output=False, start_timeout=60, report_mode=False, cwd=None, ): """Executes a single notebook locally. Parameters ------...
Prepare metadata associated with a notebook and its cells
def prepare_notebook_metadata(nb, input_path, output_path, report_mode=False): """Prepare metadata associated with a notebook and its cells Parameters ---------- nb : NotebookNode Executable notebook object input_path : str Path to input notebook output_path : str Path to ...
Assigned parameters into the appropriate place in the input notebook
def raise_for_execution_errors(nb, output_path): """Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook """ error = None for cell in nb.cel...
Limits a list of Bucket s objects based on prefix and delimiter.
def list(self, prefix='', delimiter=None): """Limits a list of Bucket's objects based on prefix and delimiter.""" return self.service._list( bucket=self.name, prefix=prefix, delimiter=delimiter, objects=True )
Returns an iterator for the data in the key or nothing if the key doesn t exist. Decompresses data on the fly ( if compressed is True or key ends with. gz ) unless raw is True. Pass None for encoding to skip encoding.
def cat( self, source, buffersize=None, memsize=2 ** 24, compressed=False, encoding='UTF-8', raw=False, ): """ Returns an iterator for the data in the key or nothing if the key doesn't exist. Decompresses data on the fly (if compressed ...
Copies source string into the destination location.
def cp_string(self, source, dest, **kwargs): """ Copies source string into the destination location. Parameters ---------- source: string the string with the content to copy dest: string the s3 location """ assert isinstance(sourc...
Returns a list of the files under the specified path name must be in the form of s3:// bucket/ prefix
def list(self, name, iterator=False, **kwargs): """ Returns a list of the files under the specified path name must be in the form of `s3://bucket/prefix` Parameters ---------- keys: optional if True then this will return the actual boto keys for files ...
Returns a list of the files under the specified path.
def listdir(self, name, **kwargs): """ Returns a list of the files under the specified path. This is different from list as it will only give you files under the current directory, much like ls. name must be in the form of `s3://bucket/prefix/` Parameters -----...
Iterates over a file in s3 split on newline.
def read(self, source, compressed=False, encoding='UTF-8'): """ Iterates over a file in s3 split on newline. Yields a line in file. """ buf = '' for block in self.cat(source, compressed=compressed, encoding=encoding): buf += block if '\n' in buf:...
Reusable by most interpreters
def translate_escaped_str(cls, str_val): """Reusable by most interpreters""" if isinstance(str_val, string_types): str_val = str_val.encode('unicode_escape') if sys.version_info >= (3, 0): str_val = str_val.decode('utf-8') str_val = str_val.replace('"'...
Translate each of the standard json/ yaml types to appropiate objects.
def translate(cls, val): """Translate each of the standard json/yaml types to appropiate objects.""" if val is None: return cls.translate_none(val) elif isinstance(val, string_types): return cls.translate_str(val) # Needs to be before integer checks elif i...
Translate dicts to scala Maps
def translate_dict(cls, val): """Translate dicts to scala Maps""" escaped = ', '.join( ["{} -> {}".format(cls.translate_str(k), cls.translate(v)) for k, v in val.items()] ) return 'Map({})'.format(escaped)
Translate list to scala Seq
def translate_list(cls, val): """Translate list to scala Seq""" escaped = ', '.join([cls.translate(v) for v in val]) return 'Seq({})'.format(escaped)
Returns a notebook object with papermill metadata loaded from the specified path.
def load_notebook_node(notebook_path): """Returns a notebook object with papermill metadata loaded from the specified path. Args: notebook_path (str): Path to the notebook file. Returns: nbformat.NotebookNode """ nb = nbformat.reads(papermill_io.read(notebook_path), as_version=4) ...
Sets the cwd during reads and writes
def cwd(self, new_path): '''Sets the cwd during reads and writes''' old_cwd = self._cwd self._cwd = new_path return old_cwd
Returns a list of the files under the specified path
def listdir(self, url): """Returns a list of the files under the specified path""" (store_name, path) = self._split_url(url) adapter = self._create_adapter(store_name) return [ "adl://{store_name}.azuredatalakestore.net/{path_to_child}".format( store_name=stor...
Read storage at a given url
def read(self, url): """Read storage at a given url""" (store_name, path) = self._split_url(url) adapter = self._create_adapter(store_name) lines = [] with adapter.open(path) as f: for line in f: lines.append(line.decode()) return lines
Write buffer to storage at a given url
def write(self, buf, url): """Write buffer to storage at a given url""" (store_name, path) = self._split_url(url) adapter = self._create_adapter(store_name) with adapter.open(path, 'wb') as f: f.write(buf.encode())
Wraps the parent class process call slightly
def preprocess(self, nb_man, resources, km=None): """ Wraps the parent class process call slightly """ with self.setup_preprocessor(nb_man.nb, resources, km=km): if self.log_output: self.log.info("Executing notebook with kernel: {}".format(self.kernel_name)) ...
This function acts as a replacement for the grandparent s preprocess method.
def papermill_process(self, nb_man, resources): """ This function acts as a replacement for the grandparent's `preprocess` method. We are doing this for the following reasons: 1. Notebooks will stop executing when they encounter a failure but not raise a `CellExcepti...
Add built - in parameters to a dictionary of parameters
def add_builtin_parameters(parameters): """Add built-in parameters to a dictionary of parameters Parameters ---------- parameters : dict Dictionary of parameters provided by the user """ with_builtin_parameters = { "pm": { "run_uuid": str(uuid4()), "curren...
Format a path with a provided dictionary of parameters
def parameterize_path(path, parameters): """Format a path with a provided dictionary of parameters Parameters ---------- path : string Path with optional parameters, as a python format string parameters : dict Arbitrary keyword arguments to fill in the path """ if parameters i...
Assigned parameters into the appropriate place in the input notebook
def parameterize_notebook(nb, parameters, report_mode=False): """Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object parameters : dict Arbitrary keyword arguments to pass as notebook parameters rep...
Returns True if key is a scan code or name of a modifier key.
def is_modifier(key): """ Returns True if `key` is a scan code or name of a modifier key. """ if _is_str(key): return key in all_modifiers else: if not _modifier_scan_codes: scan_codes = (key_to_scan_codes(name, False) for name in all_modifiers) _modifier_sca...
Returns a list of scan codes associated with this key ( name or scan code ).
def key_to_scan_codes(key, error_if_missing=True): """ Returns a list of scan codes associated with this key (name or scan code). """ if _is_number(key): return (key,) elif _is_list(key): return sum((key_to_scan_codes(i) for i in key), ()) elif not _is_str(key): raise Val...
Parses a user - provided hotkey into nested tuples representing the parsed structure with the bottom values being lists of scan codes. Also accepts raw scan codes which are then wrapped in the required number of nestings.
def parse_hotkey(hotkey): """ Parses a user-provided hotkey into nested tuples representing the parsed structure, with the bottom values being lists of scan codes. Also accepts raw scan codes, which are then wrapped in the required number of nestings. Example: parse_hotkey("alt+shift+a...
Sends OS events that perform the given * hotkey * hotkey.
def send(hotkey, do_press=True, do_release=True): """ Sends OS events that perform the given *hotkey* hotkey. - `hotkey` can be either a scan code (e.g. 57 for space), single key (e.g. 'space') or multi-key, multi-step hotkey (e.g. 'alt+F4, enter'). - `do_press` if true then press events are sent. ...
Returns True if the key is pressed.
def is_pressed(hotkey): """ Returns True if the key is pressed. is_pressed(57) #-> True is_pressed('space') #-> True is_pressed('ctrl+space') #-> True """ _listener.start_if_necessary() if _is_number(hotkey): # Shortcut. with _pressed_events_lock: ...
Calls the provided function in a new thread after waiting some time. Useful for giving the system some time to process an event without blocking the current execution flow.
def call_later(fn, args=(), delay=0.001): """ Calls the provided function in a new thread after waiting some time. Useful for giving the system some time to process an event, without blocking the current execution flow. """ thread = _Thread(target=lambda: (_time.sleep(delay), fn(*args))) thr...
Installs a global listener on all available keyboards invoking callback each time a key is pressed or released. The event passed to the callback is of type keyboard. KeyboardEvent with the following attributes:
def hook(callback, suppress=False, on_remove=lambda: None): """ Installs a global listener on all available keyboards, invoking `callback` each time a key is pressed or released. The event passed to the callback is of type `keyboard.KeyboardEvent`, with the following attributes: - `name`: ...
Invokes callback for every KEY_DOWN event. For details see hook.
def on_press(callback, suppress=False): """ Invokes `callback` for every KEY_DOWN event. For details see `hook`. """ return hook(lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)
Invokes callback for every KEY_UP event. For details see hook.
def on_release(callback, suppress=False): """ Invokes `callback` for every KEY_UP event. For details see `hook`. """ return hook(lambda e: e.event_type == KEY_DOWN or callback(e), suppress=suppress)
Hooks key up and key down events for a single key. Returns the event handler created. To remove a hooked key use unhook_key ( key ) or unhook_key ( handler ).
def hook_key(key, callback, suppress=False): """ Hooks key up and key down events for a single key. Returns the event handler created. To remove a hooked key use `unhook_key(key)` or `unhook_key(handler)`. Note: this function shares state with hotkeys, so `clear_all_hotkeys` affects it aswell. ...
Invokes callback for KEY_DOWN event related to the given key. For details see hook.
def on_press_key(key, callback, suppress=False): """ Invokes `callback` for KEY_DOWN event related to the given key. For details see `hook`. """ return hook_key(key, lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)
Invokes callback for KEY_UP event related to the given key. For details see hook.
def on_release_key(key, callback, suppress=False): """ Invokes `callback` for KEY_UP event related to the given key. For details see `hook`. """ return hook_key(key, lambda e: e.event_type == KEY_DOWN or callback(e), suppress=suppress)
Removes all keyboard hooks in use including hotkeys abbreviations word listeners record ers and wait s.
def unhook_all(): """ Removes all keyboard hooks in use, including hotkeys, abbreviations, word listeners, `record`ers and `wait`s. """ _listener.start_if_necessary() _listener.blocking_keys.clear() _listener.nonblocking_keys.clear() del _listener.blocking_hooks[:] del _listener.hand...
Whenever the key src is pressed or released regardless of modifiers press or release the hotkey dst instead.
def remap_key(src, dst): """ Whenever the key `src` is pressed or released, regardless of modifiers, press or release the hotkey `dst` instead. """ def handler(event): if event.event_type == KEY_DOWN: press(dst) else: release(dst) return False retu...
Parses a user - provided hotkey. Differently from parse_hotkey instead of each step being a list of the different scan codes for each key each step is a list of all possible combinations of those scan codes.
def parse_hotkey_combinations(hotkey): """ Parses a user-provided hotkey. Differently from `parse_hotkey`, instead of each step being a list of the different scan codes for each key, each step is a list of all possible combinations of those scan codes. """ def combine_step(step): # A sin...
Hooks a single - step hotkey ( e. g. shift + a ).
def _add_hotkey_step(handler, combinations, suppress): """ Hooks a single-step hotkey (e.g. 'shift+a'). """ container = _listener.blocking_hotkeys if suppress else _listener.nonblocking_hotkeys # Register the scan codes of every possible combination of # modfiier + main key. Modifiers have to b...