def set_folder(self, tries=3, check_access=True): """Set folder to trassir settings Args: tries (int, optional): Numbers of tris to set folder. Default 3. check_access (bool, optional): Check write access if True. Default True. """ host.stats()["run_count"] = tries try: new_folder = self.folder.mount() if check_access: self._check_path(new_folder) host.stats()["run_count"] = 0 except Exception as err: # pylint: disable=W0703 if tries: logger.warning("%s attempt failed with error: %s", tries, err) host.timeout( 1000, lambda: self.set_folder( tries=(tries - 1), check_access=check_access ), ) else: logger.error("%s attempt failed with error: %s", tries, err) raise_from_thread(err) return self._set_screenshots_folder(new_folder) if self.folder.rollback is True: host.register_finalizer(self.rollback)
def __init__(self, filename): super(MyFileHandler, self).__init__() self.__file_path = win_encode_path( os.path.join( host.settings("system_wide_options")["screenshots_folder"], filename)) self.__writer_working = False self.__msg_queue = deque(maxlen=1000) host.register_finalizer(self.__writer)
def _load_object(self, tries=5): logger.debug("Loading schedule object('%s')...", self._name) for sett in host.settings("scripts").ls(): if sett.type == "Schedule" and sett["enable"] and ( sett.name == self._name or sett.guid == self._name): obj = host.object(sett.guid) logger.debug("Found local schedule %s", sett.guid) break else: logger.warning( "Local schedule not found, get random global object with name %r", self._name) obj = host.object(self._name) try: self._name = obj.name try: obj.state("color") logger.info("Schedule %s (%s) loaded success", obj.name, obj.guid) except KeyError: raise RuntimeError( "Object {obj.name} ({obj.guid}) is not schedule".format( obj=obj)) self.__obj = obj self.__prev_color = self.color if callable(self.color_change_handler): logger.info("Add handler on color changed") host.register_finalizer(self.__del__) # Call handler with timeout need to fix bug: # Restarting schedule with not Green color # calls state changes handler twice: # with Green color and current color self.__obj.activate_on_state_changes( lambda: host.timeout(1, self._state_changes)) except EnvironmentError: if tries: logger.warning("Schedule %s not found, next try after 1000ms", self._name) host.timeout(1000, lambda: self._load_object(tries - 1)) else: raise EnvironmentError( "Schedule with name {} not found".format(self._name))
def get_logger(host_log="WARNING", popup_log="ERROR"): """Prepare and returns logger Args: host_log (str, optional): HostLogHandler level. Default "WARNING" popup_log (str, optional): PopupHandler level. Default "ERROR" Returns: logging.logger: Logger """ logger_ = logging.getLogger(__name__) logger_.setLevel("DEBUG") def _remove_handlers(): """Close and remove handlers on disable script""" for handler in logger_.handlers[:]: handler.close() logger_.removeHandler(handler) host.register_finalizer(_remove_handlers) if host_log: host_handler = HostLogHandler() host_handler.setLevel(host_log) host_formatter = logging.Formatter( "[%(levelname)-8s] %(lineno)-4s <%(funcName)s> - %(message)s" ) host_handler.setFormatter(host_formatter) logger_.addHandler(host_handler) if popup_log: popup_handler = PopupHandler() popup_handler.setLevel(popup_log) popup_formatter = logging.Formatter( fmt="<b>[%(levelname)s]</b> Line: %(lineno)s<br><i>%(message).630s</i>" ) popup_handler.setFormatter(popup_formatter) logger_.addHandler(popup_handler) return logger_
"""Set script name Args: name (str, optional): Script name, if None - parse name from parameters Returns: str: Script name """ if name: default_script_name = str(name) else: doc = getattr(main_module, "__doc__", None) or "" title = re.search(r"<title>(.+)</title>", doc) version = None if title: version = re.search(r"<version>(.+)</version>", doc) default_script_name = "{title} v{version}".format( title=title.group(1), version=version.group(1) if version else "?.?.?") if SCRIPT_NAME in DEFAULT_SCRIPT_NAMES: host.stats().parent()["name"] = default_script_name return default_script_name def __finalizer(): for finalizer in finalizers: finalizer() host.register_finalizer(__finalizer)
def get_channels(select_channels): for sett in host.settings("channels").ls(): if sett.type == "Channel" and not sett["archive_zombie_flag"]: if select_channels is None or sett.name in select_channels: grabber = get_channel_grabber(sett) if grabber and grabber["grabber_enabled"]: yield sett.guid def draw_figures(): for guid in get_channels(CHANNELS): draw( guid, text_ext(X1, Y1, X2, Y2, CUSTOM_STRING, BACKGROUND_COLOR, FONT_COLOR, FONT_SIZE), ) host.timeout(30000, draw_figures) def clear_figures(): for guid in get_channels(CHANNELS): logger.debug("clear figures on channel with guid %s", guid) host.figure_remove(guid) if not CUSTOM_STRING: raise ValueError("Empty string to display") draw_figures() host.register_finalizer(clear_figures)