def main(
    sequences: Path,
    fasta_output: Path = typer.Option(Path('input_sequences.correctedID.fasta'),
                                          help='FASTA Sequences with correct ID for Pangolin Analysis.'),
):
    from rich.traceback import install
    install(show_locals=True, width=200, word_wrap=True)
    logging.basicConfig(
        format="%(message)s",
        datefmt="[%Y-%m-%d %X]",
        level=logging.INFO,
        handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True, locals_max_string=200)],
    )
    with open(fasta_output, 'w') as fout:
        if '.gz' in Path(sequences).suffixes:
            logging.info(f'Input Sequences {sequences} in gz format provided')
            with gzip.open(sequences, 'rt') as fin:
                for name, seq in SimpleFastaParser(fin):
                    header = re.sub(r'[\|\s].*$', "", name)
                    fout.write(f'>{header}\n{seq}\n')
        else:
            logging.info(f'Input Sequences {sequences} in unzip format provided')
            with open(sequences, 'rt') as fin:
                for name, seq in SimpleFastaParser(fin):
                    header = re.sub(r'[\|\s].*$', "", name)
                    fout.write(f'>{header}\n{seq}\n')
Exemple #2
0
    def main(self):
        pretty.install()
        install()
        shell = AutoShell()
        self.init(shell)

        out_list = []
        if self.all_flag:
            for PM in self.PMs:
                pm = PM()
                out_list.extend(pm.get_all_packages())
        else:
            for package_name in self.known_packages.keys():
                try:
                    package = UniversalePackage(
                        package_name,
                        shell=shell,
                        pms_classes=self.PMs,  # не работает как надо!
                        known_packages=self.known_packages,
                    )
                except PackageManagerNotInatalled:
                    continue
                if package.is_installed():
                    ver = package.info.get("version", None)
                    if not ver:
                        out_list.append(f"{package_name}")
                    else:
                        out_list.append(f"{package_name}@{ver}")
        for line in out_list:
            print(line)

        if self.output != None:
            data = {"packages": out_list}
            with open(self.output, 'w+') as f:
                yaml.dump(data, f, default_flow_style=False)
Exemple #3
0
def main(
        newick_tree_input: Path,
        lineage_report: Path,
        aa_mutation_matrix: Path = typer.Option(None),
        leaflist: Path = typer.Option(Path('leaflist')),
        metadata_output: Path = typer.Option(Path('metadata.merged.tsv')),
):
    from rich.traceback import install
    install(show_locals=True, width=120, word_wrap=True)
    logging.basicConfig(
        format="%(message)s",
        datefmt="[%Y-%m-%d %X]",
        level=logging.INFO,
        handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)],
    )
    df_lineage_report = pd.read_csv(lineage_report, index_col=0)
    if aa_mutation_matrix:
        df_aa_change = pd.read_table(aa_mutation_matrix, index_col=0)
        df_out = pd.concat([df_lineage_report, df_aa_change], axis=1)
    else:
        df_out = df_lineage_report
    df_out.to_csv(metadata_output, sep='\t', index=True)

    tree = Phylo.read(newick_tree_input, 'newick')
    with open(leaflist, 'w') as fout:
        for node in tree.get_terminals():
            fout.write(f'{node.name}\n')
Exemple #4
0
def main(argv: List[str] = None) -> int:
    """Entry point for the CLI of the Pynguin automatic unit test generation framework.

    This method behaves like a standard UNIX command-line application, i.e.,
    the return value `0` signals a successful execution.  Any other return value
    signals some errors.  This is, e.g., the case if the framework was not able
    to generate one successfully running test case for the class under test.

    Args:
        argv: List of command-line arguments

    Returns:
        An integer representing the success of the program run.  0 means
        success, all non-zero exit codes indicate errors.
    """
    install()
    if argv is None:
        argv = sys.argv
    if len(argv) <= 1:
        argv.append("--help")
    argv = _expand_arguments_if_necessary(argv[1:])

    argument_parser = _create_argument_parser()
    parsed = argument_parser.parse_args(argv)
    _setup_output_path(parsed.config.output_path)
    _setup_logging(parsed.verbosity, parsed.log_file)

    set_configuration(parsed.config)
    with console.status("Running Pynguin..."):
        return run_pynguin().value
Exemple #5
0
    def __init__(self):
        cfg_file = Path(
            os.path.expanduser(
                os.environ.get('TIMEFRED_CONFIG_PATH', "~/.timefred.toml")))

        if cfg_file.exists():
            cfg = toml.load(cfg_file.open())
        else:
            self._create_default_config_file(cfg_file)
            cfg = {}
        super().__init__(**cfg)

        if self.dev.debugger:
            os.environ['PYTHONBREAKPOINT'] = self.dev.debugger

        if self.dev.traceback:
            try:
                if self.dev.traceback == "rich.traceback":
                    from rich.traceback import install
                    install(show_locals=True)
                else:
                    log.warning(f"Don't support {self.dev.traceback}")
            except Exception as e:
                log.error(
                    f'{e.__class__.__qualname__} caught in {self}.__init__: {e}'
                )
    def __init__(self, dataStructure):
        super(interactiveDataStructures, self).__init__()
        # rich module elements
        pretty.install()
        traceback.install()
        self.console = Console()
        # Datastructure elements
        availableDataStrutuces = {
            'DynamicArray': DynamicArray(),
            'SingleLinkedList': SinglyLinkedList(),
            'DoublyLinkedList': DoublyLinkedList(),
            'Stack': Stack(),
            'Queue': Queue(),
            'PriorityQueue': PriorityQueue()
            }

        correspondingNodes = {
            'DynamicArray': None,
            'SingleLinkedList': ListNode(None),
            'DoublyLinkedList': ListNode(None),
            'Stack': StackNode(None),
            'Queue': QueueNode(None),
            'PriorityQueue': PQNode(None)
            }

        if dataStructure in availableDataStrutuces:
            self.dataStructure = availableDataStrutuces[dataStructure]
            self.DSNode = correspondingNodes[dataStructure]
            self.DSname = dataStructure
            interactiveDataStructures.prompt = text.Text(f'({dataStructure}) ', style="bold magenta") # doesn't quite work
        else:
            raise ValueError(f'Please choose one of the following available data structure: {availableDataStrutuces.keys()}')
Exemple #7
0
def main(
        newick_tree_input: Path,
        metadata_input: Path,
        lineage_report: Path = typer.Option(
            ..., help="Pangolin lineage report CSV"),
        ref_name: str = typer.Option("MN908947.3",
                                     help="Reference/outgroup name"),
        leaflist: Path = typer.Option(
            Path('leaflist'),
            help='List of leaves/taxa to filter for in shiptv tree'),
        metadata_output: Path = typer.Option(
            'metadata.leaflist.tsv', help='Metadata for leaflist taxa'),
        max_taxa: int = typer.Option(100, help="Max taxa in leaflist"),
):
    """Prune phylo tree to taxa neighboring user taxa"""
    from rich.traceback import install
    install(show_locals=True, width=120, word_wrap=True)
    logging.basicConfig(
        format="%(message)s",
        datefmt="[%Y-%m-%d %X]",
        level=logging.INFO,
        handlers=[
            RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)
        ],
    )
    df = pd.read_table(metadata_input, index_col=0)
    logging.info(
        f'Read metadata table "{metadata_input}" with {df.shape[0]} rows.')
    tree: Tree = Phylo.read(newick_tree_input, "newick")
    n_taxa = tree.count_terminals()
    logging.info(f'Read tree "{newick_tree_input}" with {n_taxa}.')
    if n_taxa <= max_taxa:
        logging.info(
            f'No pruning of tree required. Number of taxa ({n_taxa}) '
            f'less than/equal to max taxa desired in tree ({max_taxa}). '
            f'Writing leaflist "{leaflist}" with all {n_taxa} taxa.')
        write_leaflist((n.name for n in tree.get_terminals()), leaflist)
        logging.info(f'Symlinking "{metadata_output}" to "{metadata_input}".')
        metadata_output.symlink_to(metadata_input.resolve())
        sys.exit(0)
    df_lineage_report = pd.read_csv(lineage_report, index_col=0)
    logging.info(
        f'Read Pangolin lineage report with {df_lineage_report.index.size} rows.'
    )
    user_taxa = set(df_lineage_report.index)
    logging.info(f'User taxa in tree determined to be {user_taxa}')
    logging.info(
        f'Getting neighboring nodes for user taxa up to {max_taxa} taxa in total.'
    )
    clade_neighbors = get_neighbors(tree, user_taxa, max_taxa - 1)
    logging.info(
        f'Found {len(clade_neighbors - user_taxa)} neighboring taxa to {len(user_taxa)} '
        f'user taxa. Writing leaf list.')
    clade_neighbors.add(ref_name)
    write_leaflist(clade_neighbors, leaflist)
    df.loc[list(clade_neighbors & set(df.index)), :].to_csv(metadata_output,
                                                            sep="\t")
Exemple #8
0
def _rich_logger(log_type: int = logging.INFO) -> logging.Logger:
    r_traceback.install()

    logging.basicConfig(level=log_type,
                        format='%(message)s',
                        datefmt="[%c]",
                        handlers=[r_logging.RichHandler()])

    return logging.getLogger("rich")
Exemple #9
0
def torch_traceback():

    from rich.traceback import install
    install(show_locals=True)

    def repr(self):
        return f"Tensor<{', '.join(map(str, self.shape))}>"

    torch.Tensor.__repr__ = repr
 def __init__(self, config: ExperimentConfig):
     self.tb_global_step = 0
     self.custom_stats_format = None
     self.config = config
     self.device = config.device
     try:
         from rich.traceback import install
         install()
     except ImportError:
         print('Note: Rich text traceback avaliable by pip install rich')
Exemple #11
0
 def __init__(self, cache_folder='cache', database_folder='database'):
     self.console = Console()
     install()
     self.cache = Cache(cache_folder)
     self.api = Api(self.cache)
     self.database = Database()
     self.database_folder = database_folder
     self.champion_names = None
     self.selected_champion = ''
     self.is_running = True
Exemple #12
0
 def __init__(self):
     self.core = Core()
     self.session = PromptSession(reserve_space_for_menu=6, complete_in_thread=True)
     self.headless = False
     self.console = None
     self.table = None
     self.slugs = None
     self.tipsDatabase = None
     self.completer = None
     self.os = platform.system()
     install()
Exemple #13
0
 def __init__(self):
     self.core = Core()
     self.session = PromptSession(reserve_space_for_menu=6)
     self.headless = False
     self.console = None
     self.table = None
     self.cfSlugs = None
     self.wowiSlugs = None
     self.completer = None
     self.os = platform.system()
     install()
Exemple #14
0
    def main(self, package_name: str):
        pretty.install()
        install()
        shell = AutoShell()
        self.init(shell)

        package = UniversalePackage(
            package_name,
            shell=shell,
            pms_classes=self.PMs,
            auto_update_conf=not self.no_auto_update_conf)
        package.install()
Exemple #15
0
def main(filename, premodel=None):
    global current_line, model
    if premodel == None:
        model = usemodel.load()
    else:
        model = premodel
    # print the intro
    rich.print("[yellow]Hello From The Alter Community[/yellow]")
    install(extra_lines=8, show_locals=True)
    if str(filename).endswith(".altr") is False:
        raise Exception("File must end with .altr")
    # load file and scan for errors, print out a custom message if were errs
    lines = []
    with open(filename, "r") as file:
        raw = file.read().split("\n")
        for i in raw:
            lines.append(i)
    out = []
    if filename.startswith("fizzbuzz"):
        filename = "Fdf"
    else:
        filename = None
    for i in lines:
        current_line += 1
        line_out = top_level(i, fname=filename)
        if line_out is not None and "ignore" not in str(line_out):
            out.append(line_out)
    print("\n")
    time.sleep(1.5)
    console = Console()
    table = Table(show_header=True, header_style="bold blue", show_lines=True)
    table.add_column("Name")
    table.add_column("Type", justify="right")
    table.add_column("Value")
    for i in variables.keys():
        table.add_row(i, str(type(variables[i])), str(variables[i]))
    console.print(table)
    table = Table(show_header=True, header_style="bold blue", show_lines=True)
    table.add_column("Order")
    for i in order:
        table.add_row(str(i))
    console.print(table)
    table = Table(show_header=True, header_style="bold blue", show_lines=True)
    table.add_column("Line #")
    table.add_column("Line Content")
    for x, i in enumerate(lines):
        table.add_row(str(x + 1), i)
    console.print(table)

    rich.print("[bold green]No Errors![/bold green]")
    rich.print("[bold blue]Program exited with code 0[/bold blue]")
    return out
Exemple #16
0
def main(metadata_input: Path,
         pangolin_report: Path,
         metadata_output: Path = typer.Option(Path('metadata.merged.tsv')),
         aa_mutation_matrix: Optional[Path] = typer.Option(
             None, help='Amino acid mutation matrix TSV'),
         select_metadata_fields: Optional[str] = typer.Option(
             None,
             help='Comma-delimited list of metadata fields to output. '
             'If unset, all metadata fields will be output.')):
    """Merge a metadata table, Pangolin results table and AA mutation matrix into one table."""
    from rich.traceback import install
    install(show_locals=True, width=120, word_wrap=True)
    logging.basicConfig(
        format="%(message)s",
        datefmt="[%Y-%m-%d %X]",
        level=logging.INFO,
        handlers=[
            RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)
        ],
    )
    df_metadata = pd.read_table(metadata_input, index_col=0)
    logging.info(
        f'Read metadata table "{metadata_input}" with '
        f'{df_metadata.shape[0]} rows and {df_metadata.shape[1]} columns')
    if select_metadata_fields:
        logging.info(f'Selecting specified metadata fields/columns from '
                     f'"{metadata_input}": {select_metadata_fields}')
        df_metadata = select_fields(df_metadata, select_metadata_fields)
    dfs = [df_metadata]
    df_pangolin = read_pangolin_report(pangolin_report)
    dfs.append(df_pangolin)
    if aa_mutation_matrix:
        dfs.append(pd.read_table(aa_mutation_matrix, index_col=0))
    logging.info(f'Merging {len(dfs)} dataframes on index')
    df_merged = pd.concat(dfs, axis=1)
    if 'Pango_lineage' in df_merged.columns:
        df_merged['Pango_lineage'] = df_merged['Pango_lineage'].combine_first(
            df_pangolin['lineage'])
    if 'Pangolin_version' in df_merged.columns:
        df_merged['Pangolin_version'] = df_merged[
            'Pangolin_version'].combine_first(
                df_pangolin['pangoLEARN_version'])
    logging.info(
        f'Writing merged dataframe with shape {df_merged.shape} to "{metadata_output}".'
    )
    df_merged.to_csv(metadata_output, sep='\t', index=True)
    logging.info(
        f'Wrote merged dataframe with shape {df_merged.shape} to "{metadata_output}".'
    )
Exemple #17
0
def main():
    # set rich as default backtrace logger
    install()

    console = Console()

    # set up parser for command line arguments
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "mode",
        metavar="mode",
        type=str,
        help=
        "The type of operation to be performed on the database: create, delete, or access"
    )
    parser.add_argument(
        "source",
        metavar="source",
        type=str,
        help="The path to the database file to be accessed or created")
    parser.add_argument(
        "--query",
        type=str,
        help=
        "If accessing the database, this must be provided as the query to be run"
    )
    parser.add_argument(
        "--infinite",
        action="store_true",
        help=
        "Set this flag to open a session to the database to run multiple queries"
    )
    parser.add_argument(
        "--embedded",
        action="store_true",
        help="Set this flag to only output JSON for use in other applications")
    args = vars(parser.parse_args())

    # main logic occurs -- split based on mode
    mode = args["mode"].lower()
    source = args["source"]
    if mode == "create":
        create(source)
    elif mode == "delete":
        delete(source, console)
    elif mode == "access":
        access(source, args["query"], args["infinite"], args["embedded"],
               console)
Exemple #18
0
def main():
    traceback.install(width=200, word_wrap=True)
    console.print(rf"""[bold blue]
     ██████  ██████   ██████  ██   ██ ██ ███████ ████████ ███████ ███    ███ ██████  ██      ███████ 
    ██      ██    ██ ██    ██ ██  ██  ██ ██         ██    ██      ████  ████ ██   ██ ██      ██      
    ██      ██    ██ ██    ██ █████   ██ █████      ██    █████   ██ ████ ██ ██████  ██      █████ 
    ██      ██    ██ ██    ██ ██  ██  ██ ██         ██    ██      ██  ██  ██ ██      ██      ██    
     ██████  ██████   ██████  ██   ██ ██ ███████    ██    ███████ ██      ██ ██      ███████ ███████ 
        """)

    console.print('[bold blue]Run [green]cookietemple --help [blue]for an overview of all commands\n')

    # Is the latest cookietemple version installed? Upgrade if not!
    if not UpgradeCommand.check_cookietemple_latest():
        console.print('[bold blue]Run [green]cookietemple upgrade [blue]to get the latest version.')
    cookietemple_cli()
Exemple #19
0
    def __init__(self):
        from rich.traceback import install
        install()
        import colorama
        colorama.init()

        self.name: str = 'command'
        self.entry_point: str = 'command'
        self.args: List[Argument] = []
        self.mutually_exclusive_args: List[MutuallyExclusiveArgumentGroup] = []
        self.argument_groups: List[ArgumentGroup] = []
        self.subcommands: List[Type[Subcommand]] = []
        self._update_meta()

        self.parser: argparse.ArgumentParser = self._create_parser()
        argcomplete.autocomplete(self.parser)
        self.parsed_args: Any = self.parser.parse_args()
        self.process_args()
Exemple #20
0
def update_verbosity(debug):
    """Set the logging verbosity according to the settings object.

    Also enable rich tracebacks in debug mode.
    """
    if debug:
        logger.setLevel(SPAM)

        try:
            from rich.traceback import install
            install(show_locals=True)
            logger.debug('Using rich.traceback')
        except Exception as error:
            # since this is optional, just skip all exceptions
            if not isinstance(error, ImportError):
                logger.debug('Cannot use rich.traceback: %s', error)
    else:
        logger.setLevel(logging.INFO)
Exemple #21
0
    def start(self, argv):
        if argv[1:]:
            for argv in argv[1:]:
                try:
                    getattr(self, argv)()
                except AttributeError:
                    print('help msg')
        else:
            from base.shell import MainShell
            from rich.traceback import install

            install()
            Shell = MainShell()

            while True:
                try:
                    Shell.cmdloop()
                except KeyboardInterrupt:
                    print('')
Exemple #22
0
    def main(self, package_name: str):
        pretty.install()
        install()
        shell = AutoShell()
        self.init(shell)

        data = {}
        for pm in self.PMs:
            try:
                out = pm(shell=shell).search(package_name)
                if out != {}:
                    data[pm.name] = out
            except NotImplementedError as e:
                logger.warning(
                    f"{pm.name} not have search method!")  # , exc_info=True)

        if self.list_mode:
            print_search_results(data)
        else:
            print_info(data)
Exemple #23
0
def update_verbosity(debug):
    """Set the logging verbosity according to the settings object.

    Also enable rich tracebacks in debug mode.
    """
    # pylint really doesn't like what I'm doing with rich.traceback here
    # pylint: disable=broad-except,import-error,import-outside-toplevel
    if debug:
        logger.setLevel(SPAM)

        try:
            from rich.traceback import install
            install(show_locals=True)
            logger.debug('Using rich.traceback')
        except Exception as error:
            # since this is optional, just skip all exceptions
            if not isinstance(error, ImportError):
                logger.debug('Cannot use rich.traceback: %s', error)
    else:
        logger.setLevel(logging.INFO)
def main(nextclade_csv: Path, metadata_output: Path):
    from rich.traceback import install
    install(show_locals=True, width=120, word_wrap=True)
    logging.basicConfig(
        format="%(message)s",
        datefmt="[%Y-%m-%d %X]",
        level=logging.INFO,
        handlers=[
            RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)
        ],
    )
    df_nextclade = pd.read_table(nextclade_csv, sep=';')
    # remove surrounding brackets, split on ',' to get Series of list of str AA mutations
    aasubs: pd.Series = df_nextclade['aaSubstitutions'].str.replace(
        r'^(\(|\))$', '', regex=True).str.split(',')
    sample_aas = sample_to_aa_mutations(aasubs, df_nextclade['seqName'])
    samples = list(sample_aas.keys())
    unique_aas = get_sorted_aa_mutations(sample_aas)
    arr_aas = fill_aa_mutation_matrix(sample_aas, samples, unique_aas)
    dfaa = pd.DataFrame(arr_aas, index=samples, columns=unique_aas)
    dfaa.to_csv(metadata_output, sep='\t')
Exemple #25
0
def main():
    traceback.install(width=200, word_wrap=True)
    print(r"""[bold blue]
         ██████  ██    ██ ██████  ███████ 
        ██    ██ ██    ██ ██   ██ ██      
        ██    ██ ██    ██ ██████  █████ 
        ██ ▄▄ ██ ██    ██ ██   ██ ██    
         ██████   ██████  ██████  ███████ 
            ▀▀  
        """)

    print(
        '[bold blue]Run [green]qube --help [blue]for an overview of all commands\n'
    )

    # Is the latest qube version installed? Upgrade if not!
    if not UpgradeCommand.check_qube_latest():
        print(
            '[bold blue]Run [green]qube upgrade [blue]to get the latest version.'
        )
    qube_cli()
Exemple #26
0
def test_handler():
    console = Console(file=io.StringIO(), width=100, color_system=None)
    expected_old_handler = sys.excepthook

    def level1():
        level2()

    def level2():
        return 1 / 0

    try:
        old_handler = install(console=console)
        try:
            level1()
        except Exception:
            exc_type, exc_value, traceback = sys.exc_info()
            sys.excepthook(exc_type, exc_value, traceback)
            rendered_exception = console.file.getvalue()
            print(repr(rendered_exception))
            assert "Traceback" in rendered_exception
            assert "ZeroDivisionError" in rendered_exception

            frame_blank_line_possible_preambles = (
                # Start of the stack rendering:
                "╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮",
                # Each subsequent frame (starting with the file name) should then be preceded with a blank line:
                "│" + (" " * 98) + "│",
            )
            for frame_start in re.finditer(
                    "^│ .+rich/tests/test_traceback\.py:",
                    rendered_exception,
                    flags=re.MULTILINE,
            ):
                frame_start_index = frame_start.start()
                for preamble in frame_blank_line_possible_preambles:
                    preamble_start, preamble_end = (
                        frame_start_index - len(preamble) - 1,
                        frame_start_index - 1,
                    )
                    if rendered_exception[
                            preamble_start:preamble_end] == preamble:
                        break
                else:
                    pytest.fail(
                        f"Frame {frame_start[0]} doesn't have the expected preamble"
                    )
    finally:
        sys.excepthook = old_handler
        assert old_handler == expected_old_handler
Exemple #27
0
def main() -> None:
    traceback.install(width=200, word_wrap=True)
    print(r"""[bold blue]
  ██████  ▄████▄  ▄▄▄█████▓ ▒█████   ▒█████   ██▓     ▄▄▄▄    ▒█████  ▒██   ██▒
▒██    ▒ ▒██▀ ▀█  ▓  ██▒ ▓▒▒██▒  ██▒▒██▒  ██▒▓██▒    ▓█████▄ ▒██▒  ██▒▒▒ █ █ ▒░
░ ▓██▄   ▒▓█    ▄ ▒ ▓██░ ▒░▒██░  ██▒▒██░  ██▒▒██░    ▒██▒ ▄██▒██░  ██▒░░  █   ░
  ▒   ██▒▒▓▓▄ ▄██▒░ ▓██▓ ░ ▒██   ██░▒██   ██░▒██░    ▒██░█▀  ▒██   ██░ ░ █ █ ▒
▒██████▒▒▒ ▓███▀ ░  ▒██▒ ░ ░ ████▓▒░░ ████▓▒░░██████▒░▓█  ▀█▓░ ████▓▒░▒██▒ ▒██▒
▒ ▒▓▒ ▒ ░░ ░▒ ▒  ░  ▒ ░░   ░ ▒░▒░▒░ ░ ▒░▒░▒░ ░ ▒░▓  ░░▒▓███▀▒░ ▒░▒░▒░ ▒▒ ░ ░▓ ░
░ ░▒  ░ ░  ░  ▒       ░      ░ ▒ ▒░   ░ ▒ ▒░ ░ ░ ▒  ░▒░▒   ░   ░ ▒ ▒░ ░░   ░▒ ░
░  ░  ░  ░          ░      ░ ░ ░ ▒  ░ ░ ░ ▒    ░ ░    ░    ░ ░ ░ ░ ▒   ░    ░
      ░  ░ ░                   ░ ░      ░ ░      ░  ░ ░          ░ ░   ░    ░
         ░                                                 ░
    """)
    print(
        "[bold blue]Run [green]sc-toolbox --help [blue]for an overview of all commands\n"
    )

    # Is the latest sc-toolbox version installed? Upgrade if not!
    if not UpgradeCommand.check_sc_toolbox_latest():
        print(
            "[bold blue]Run [green]sc-toolbox upgrade [blue]to get the latest version."
        )
    sc_toolbox_cli()  # type: ignore
Exemple #28
0
def _rich_logger(log_type: int = logging.INFO) -> logging.Logger:
    """Logs information with the rich library with fancy tracebacks.

    Args:
        log_type (:obj:`t.Union[str, int]`, optional): The level of logging to be used.
            Defaults to None.
        store_file (bool, optional): If the logs want to be stored.

    Returns:
        :obj:`logging.Logger`: The object that the bot will use to log information to.

    Raises:
        IndexError: If `log_type` isn't within log_types.

    """
    r_traceback.install()

    logging.basicConfig(level=log_type,
                        format='%(message)s',
                        datefmt="[%c]",
                        handlers=[r_logging.RichHandler()])

    # different message types: info, debug, warning, critical
    return logging.getLogger("rich")
Exemple #29
0
    def main(self, package_name):
        pretty.install()
        install()
        shell = AutoShell()
        self.init(shell)

        logger.debug(
            f"Args:\n\tpackage_name = {package_name},\n\tpm_names = {self.pm_names}\n\tall = {self.all_flag}\n\toffline = {self.offline}"
        )

        package = UniversalePackage(package_name,
                                    shell=shell,
                                    pms_classes=self.PMs,
                                    known_packages=self.known_packages)

        package.update_package_info(all_pm=self.all_flag)
        info = package.info
        if info == {}:
            logger.error("Package Does Not Found")
            return

        print_info(info)
        if package_name not in self.known_packages:
            update_user_known_package(package_name, package.config)
def test_handler():
    console = Console(file=io.StringIO(), width=100, color_system=None)
    expected_old_handler = sys.excepthook
    try:
        old_handler = install(console=console)
        try:
            1 / 0
        except Exception:
            exc_type, exc_value, traceback = sys.exc_info()
            sys.excepthook(exc_type, exc_value, traceback)
            rendered_exception = console.file.getvalue()
            print(repr(rendered_exception))
            assert "Traceback" in rendered_exception
            assert "ZeroDivisionError" in rendered_exception
    finally:
        sys.excepthook = old_handler
        assert old_handler == expected_old_handler