def installPackages(self, logFile: io.IOBase = tempfile.TemporaryFile, outputLogFile: io.IOBase = tempfile.TemporaryFile): self._unlock() logFile, outputLogFile = logFile(), outputLogFile() oldStdError, oldStdOut = os.dup(sys.stderr.fileno()), os.dup( sys.stdout.fileno()) os.dup2(outputLogFile.fileno(), sys.stderr.fileno()) os.dup2(outputLogFile.fileno(), sys.stdout.fileno()) try: self.pkgManager.do_install(logFile.fileno()) except Exception as e: self.installError = (e, traceback.format_exc()) os.dup2(oldStdError, sys.stderr.fileno()) os.dup2(oldStdOut, sys.stdout.fileno()) self._lock() logFile.seek(0) outputLogFile.seek(0) self.updateCache() [package.update(install=True) for package in self.pkgList.values()] for line in (line.decode().replace("\n", "") for line in logFile.readlines()): matches = re.match(r'^pmerror:([^:]+):([^:]+):(.*)$', line) if matches: pkgName, _, error = matches[1], matches[2], matches[3] self.pkgList[pkgName].errors += [error] logFile.seek(0) self.logFile, self.outputLogFile = logFile, outputLogFile
def tracingCPUMEM(vm: dict, f_input: IOBase, f_output: IOBase): # Checking file first line. line = f_input.readline() line_cols = line.split(';') if (line_cols[1] != CPU_MEM_START): sys.exit(f"Wrong file format:'{f_input.name}'.") previous_time = datetime.strptime(line_cols[0][0:30], CPU_MEM_TIME_MASK) total_time = timedelta() for line in f_input.readlines(): line_cols = line.split(';') # Checking file last line. if (line_cols[1] == CPU_MEM_END): break curr_time = datetime.strptime(line_cols[0][0:30], CPU_MEM_TIME_MASK) total_time += (curr_time - previous_time) tt_seconds = total_time.total_seconds() previous_time = curr_time # Loop through each vm entry in "line" for vm_entry in line_cols[1:]: vm_cols = vm_entry.split() # If entry corresponds to the current vm, register values. if (vm_cols[0] == vm["name"]): outputPAJEVariable(tt_seconds, vm["name"], 'MEM', vm_cols[1], f_output) outputPAJEVariable(tt_seconds, vm["name"], 'CPU', vm_cols[3], f_output)
def __init__(self, archivo: IOBase, tablaDeSimbolos: dict ): #se ejecuta solo al crear el Lexico (constructor) self.x = 0 self.y = 0 self.codigoFuente = archivo.readlines() self.tablaDeSimbolos = tablaDeSimbolos self.reconocedores = reconocedores self.caractesIgnorados = whitespace self.caractesDeCierre = '\n'
def parse_stream(self, stream: io.IOBase) -> List[Statement]: """ Parses a stream :param stream: The stream to parse :return: The statements in the stream """ statements = [] lines = list(map(lambda x: x.strip(), stream.readlines())) for line in lines: statement = self.parse_line(line) if statement is not None: statements.append(statement) return statements
def _get_objects_from_file(self, obj, prefix_char: str, file: IOBase, preload: bool = False): if not isinstance(file, IOBase): raise ValueError("'file' argument must be an opend file") try: lines = file.readlines() lines = [ line.strip()[1:] for line in lines if len(line) > 1 and line.strip()[0] == prefix_char ] # filter out invalid lines and strip them if not lines: self._logger.error("No data can be retrieved from file.") return [] if preload: return instance_worker(self._session, obj, lines) else: return instance_generator(self._session, obj, lines) finally: file.close()
def _read_file(input: io.IOBase) -> Optional[Font]: lines = [x for x in input.readlines() if not x.startswith("Comment")] lines = [x[:-1] if x.endswith("\n") else x for x in lines] # check first/last line if not lines[0].startswith("StartFontMetrics") or not lines[-1].startswith( "EndFontMetrics" ): return None out_font = Font() # FontDescriptor out_font_descriptor = FontDescriptor().set_parent(out_font) out_font_descriptor["FontName"] = AdobeFontMetrics._find_and_parse_as_string( lines, "FontName" ) out_font_descriptor["FontFamily"] = AdobeFontMetrics._find_and_parse_as_string( lines, "FamilyName" ) # FontStretch # FontWeight # Flags # FontBBox # ItalicAngle out_font_descriptor["Ascent"] = AdobeFontMetrics._find_and_parse_as_float( lines, "Ascender" ) out_font_descriptor["Descent"] = AdobeFontMetrics._find_and_parse_as_float( lines, "Descender" ) # Leading out_font_descriptor["CapHeight"] = AdobeFontMetrics._find_and_parse_as_float( lines, "CapHeight" ) out_font_descriptor["XHeight"] = AdobeFontMetrics._find_and_parse_as_float( lines, "XHeight" ) # StemV out_font_descriptor["StemV"] = AdobeFontMetrics._find_and_parse_as_float( lines, "StemV" ) # StemH out_font_descriptor["StemH"] = AdobeFontMetrics._find_and_parse_as_float( lines, "StemH" ) # AvgWidth out_font_descriptor["AvgWidth"] = AdobeFontMetrics._find_and_parse_as_float( lines, "AvgWidth" ) # MaxWidth out_font_descriptor["MaxWidth"] = AdobeFontMetrics._find_and_parse_as_float( lines, "MaxWidth" ) # MissingWidth out_font_descriptor["MissingWidth"] = AdobeFontMetrics._find_and_parse_as_float( lines, "MissingWidth" ) # FontFile # FontFile2 # FontFile3 out_font_descriptor["CharSet"] = AdobeFontMetrics._find_and_parse_as_integer( lines, "Characters" ) # Font out_font["Type"] = "Font" out_font["Subtype"] = "Type1" out_font["Name"] = out_font_descriptor["FontName"] out_font["BaseFont"] = out_font_descriptor["FontName"] widths = List().set_parent(out_font) avg_char_width = 0 avg_char_width_norm = 0 first_char = None last_char = None char_metrics_lines = lines[ lines.index( [x for x in lines if x.startswith("StartCharMetrics")][0] ) : lines.index("EndCharMetrics") + 1 ] char_metrics_lines = char_metrics_lines[1:-1] for cml in char_metrics_lines: tmp = { y.split(" ")[0]: y.split(" ")[1] for y in [x.strip() for x in cml.split(";")] if " " in y } # determine char ch = -1 if "C" in tmp: ch = int(tmp["C"]) if "CH" in tmp: ch = int(tmp["CH"][1:-1], 16) if (first_char is None or ch < first_char) and ch != -1: first_char = ch if (last_char is None or ch > last_char) and ch != -1: last_char = ch w = float(tmp["WX"]) if ch != -1 and w != 0: avg_char_width += w avg_char_width_norm += 1 widths.append(Decimal(w)) out_font["FirstChar"] = Decimal(first_char) out_font["LastChar"] = Decimal(last_char) out_font["Widths"] = widths if out_font_descriptor["AvgWidth"] is None: out_font_descriptor["AvgWidth"] = round( Decimal(avg_char_width / avg_char_width_norm), 2 ) if out_font_descriptor["MaxWidth"] is None: out_font_descriptor["MaxWidth"] = max(widths) out_font["FontDescriptor"] = out_font_descriptor # return return out_font
def read_to_object(self, f: IOBase): records = list(read_csv(f.readlines())) return records
def text_load(self, fobj: io.IOBase) -> list: texts = fobj.readlines() return texts
def _read_export_file( keep: gkeepapi.Keep, fh: io.IOBase, note: Optional[gkeepapi.node.TopLevelNode] = None, ) -> gkeepapi.node.TopLevelNode: lines = fh.readlines() title = "" color = gkeepapi.node.ColorValue.White pinned = False archived = False labels = set() items = [] # Extract the title i = 0 m = TITLE_RE.search(lines[i]) if m: title = m.group(1) i += 1 # Extract all the options options = [] while i < len(lines): m = OPTION_RE.search(lines[i]) if not m: break options.append(m.group(1)) i += 1 # Process the options for option in options: parts = option.split(" ", 1) if parts[0] == "pinned": pinned = True elif parts[0] == "archived": archived = True elif parts[0] == "color": if len(parts) == 2: try: color = gkeepapi.node.ColorValue(parts[1].upper()) except ValueError: logger.warning("Unknown color option: %s", parts[1]) elif parts[0] == "label": labels.add(parts[1]) else: logger.warning("Unknown option: %s", parts[0]) # Initialize note (if necessary) if note is None: labels.add(args.label) if len(lines) > i and LISTITEM_RE.search(lines[i]): note = gkeepapi.node.List() else: note = gkeepapi.node.Note() # Extract content if isinstance(note, gkeepapi.node.List): # Extract list items first = True item = [] indented = False checked = False while i < len(lines): m = LISTITEM_RE.search(lines[i]) if not m: if first: logger.warning("Invalid listitem entry: %s", lines[i]) else: item.append(lines[i]) else: if not first: items.append((indented, checked, "\n".join(item))) item = [] indented_str, checked_str, content = m.groups() indented = bool(indented_str) checked = " " != checked_str item.append(content) first = False i += 1 if not first: items.append((indented, checked, "\n".join(item))) # Sync up items to the list i = 0 list_items = note.items sort = random.randint(1000000000, 9999999999) while True: a_ok = i < len(items) b_ok = i < len(list_items) # Update an existing item if a_ok and b_ok: indented, checked, content = items[i] list_item = list_items[i] if indented != list_item.indented: list_item.indented = indented if checked != list_item.checked: list_item.checked = checked if content != list_item.text: list_item.text = content sort = int(list_item.sort) # Create a new item elif a_ok: indented, checked, content = items[i] list_item = note.add(content, checked, sort) if indented: list_item.indent() sort -= gkeepapi.node.List.SORT_DELTA # Remove a deleted item elif b_ok: list_items[i].delete() else: break i += 1 else: text = "\n".join(lines[i:]) if note.text != text: note.text = text # Apply labels note_labels = set((label.name for label in note.labels.all())) new_labels = labels - note_labels del_labels = note_labels - labels for label in new_labels: note.labels.add(keep.findLabel(label, True)) for label in del_labels: note.labels.remove(keep.findLabel(label)) # Apply all other changes if note.title != title: note.title = title if note.pinned != pinned: note.pinned = pinned if note.archived != archived: note.archived = archived if note.color != color: note.color = color return note