Python colorama.deinit() Examples

The following are 11 code examples of colorama.deinit(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module colorama , or try the search function .
Example #1
Source File: aesthetics.py    From BrundleFuzz with MIT License 5 votes vote down vote up
def stop(self):
        self.m_info("Restoring terminal...")
        colorama.deinit() 
Example #2
Source File: aesthetics.py    From BrundleFuzz with MIT License 5 votes vote down vote up
def stop(self):
        self.m_info("Restoring terminal...")
        colorama.deinit() 
Example #3
Source File: pipelines_resource_provider.py    From azure-devops-cli-extension with MIT License 5 votes vote down vote up
def poll_connection_ready(organization, project, connection_id):
    import colorama
    colorama.init()
    import humanfriendly
    import time
    with humanfriendly.Spinner(label="Checking resource readiness") as spinner:  # pylint: disable=no-member
        se_client = get_service_endpoint_client(organization)
        while True:
            spinner.step()
            time.sleep(0.5)
            service_endpoint = se_client.get_service_endpoint_details(project, connection_id)
            if service_endpoint.is_ready:
                break
    colorama.deinit() 
Example #4
Source File: color.py    From incubator-ariatosca with Apache License 2.0 5 votes vote down vote up
def _restore_terminal():
    colorama.deinit() 
Example #5
Source File: diff.py    From pep8radius with MIT License 5 votes vote down vote up
def print_diff(diff, color=True):
    """Pretty printing for a diff, if color then we use a simple color scheme
    (red for removed lines, green for added lines)."""
    import colorama

    if not diff:
        return

    if not color:
        colorama.init = lambda autoreset: None
        colorama.Fore.RED = ''
        colorama.Back.RED = ''
        colorama.Fore.GREEN = ''
        colorama.deinit = lambda: None

    colorama.init(autoreset=True)  # TODO use context_manager
    for line in diff.splitlines():
        if line.startswith('+') and not line.startswith('+++ '):
            # Note there shouldn't be trailing whitespace
            # but may be nice to generalise this
            print(colorama.Fore.GREEN + line)
        elif line.startswith('-') and not line.startswith('--- '):
            split_whitespace = re.split('(\s+)$', line)
            if len(split_whitespace) > 1:  # claim it must be 3
                line, trailing, _ = split_whitespace
            else:
                line, trailing = split_whitespace[0], ''
            print(colorama.Fore.RED + line, end='')
            # give trailing whitespace a RED background
            print(colorama.Back.RED + trailing)
        elif line == '\ No newline at end of file':
            # The assumption here is that there is now a new line...
            print(colorama.Fore.RED + line)
        else:
            print(line)
    colorama.deinit() 
Example #6
Source File: gtfoblookup.py    From GTFOBLookup with GNU General Public License v3.0 5 votes vote down vote up
def exit():
    """Exits the program"""
    colorama.deinit()
    sys.exit() 
Example #7
Source File: spin.py    From pipenv with MIT License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        # type: (Any, Any)
        """
        Get a spinner object or a dummy spinner to wrap a context.

        Keyword Arguments:
        :param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
        :param str start_text: Text to start off the spinner with (default: {None})
        :param dict handler_map: Handler map for signals to be handled gracefully (default: {None})
        :param bool nospin: If true, use the dummy spinner (default: {False})
        :param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True)
        """

        self.handler = handler
        colorama.init()
        sigmap = {}  # type: TSignalMap
        if handler:
            sigmap.update({signal.SIGINT: handler, signal.SIGTERM: handler})
        handler_map = kwargs.pop("handler_map", {})
        if os.name == "nt":
            sigmap[signal.SIGBREAK] = handler
        else:
            sigmap[signal.SIGALRM] = handler
        if handler_map:
            sigmap.update(handler_map)
        spinner_name = kwargs.pop("spinner_name", "bouncingBar")
        start_text = kwargs.pop("start_text", None)
        _text = kwargs.pop("text", "Running...")
        kwargs["text"] = start_text if start_text is not None else _text
        kwargs["sigmap"] = sigmap
        kwargs["spinner"] = getattr(Spinners, spinner_name, "")
        write_to_stdout = kwargs.pop("write_to_stdout", True)
        self.stdout = kwargs.pop("stdout", sys.stdout)
        self.stderr = kwargs.pop("stderr", sys.stderr)
        self.out_buff = StringIO()
        self.write_to_stdout = write_to_stdout
        self.is_dummy = bool(yaspin is None)
        self._stop_spin = None  # type: Optional[threading.Event]
        self._hide_spin = None  # type: Optional[threading.Event]
        self._spin_thread = None  # type: Optional[threading.Thread]
        super(VistirSpinner, self).__init__(*args, **kwargs)
        if DISABLE_COLORS:
            colorama.deinit() 
Example #8
Source File: aesthetics.py    From BrundleFuzz with MIT License 4 votes vote down vote up
def stop(self):
        self.m_info("Restoring terminal...")
        colorama.deinit() 
Example #9
Source File: screen.py    From bandit with Apache License 2.0 4 votes vote down vote up
def report(manager, fileobj, sev_level, conf_level, lines=-1):
    """Prints discovered issues formatted for screen reading

    This makes use of VT100 terminal codes for colored text.

    :param manager: the bandit manager object
    :param fileobj: The output file object, which may be sys.stdout
    :param sev_level: Filtering severity level
    :param conf_level: Filtering confidence level
    :param lines: Number of lines to report, -1 for all
    """

    if IS_WIN_PLATFORM and COLORAMA:
        colorama.init()

    bits = []
    if not manager.quiet or manager.results_count(sev_level, conf_level):
        bits.append(header("Run started:%s", datetime.datetime.utcnow()))

        if manager.verbose:
            bits.append(get_verbose_details(manager))

        bits.append(header("\nTest results:"))
        bits.append(get_results(manager, sev_level, conf_level, lines))
        bits.append(header("\nCode scanned:"))
        bits.append('\tTotal lines of code: %i' %
                    (manager.metrics.data['_totals']['loc']))

        bits.append('\tTotal lines skipped (#nosec): %i' %
                    (manager.metrics.data['_totals']['nosec']))

        bits.append(get_metrics(manager))
        skipped = manager.get_skipped()
        bits.append(header("Files skipped (%i):", len(skipped)))
        bits.extend(["\t%s (%s)" % skip for skip in skipped])
        do_print(bits)

    if fileobj.name != sys.stdout.name:
        LOG.info("Screen formatter output was not written to file: %s, "
                 "consider '-f txt'", fileobj.name)

    if IS_WIN_PLATFORM and COLORAMA:
        colorama.deinit() 
Example #10
Source File: spin.py    From vistir with ISC License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        # type: (Any, Any)
        """
        Get a spinner object or a dummy spinner to wrap a context.

        Keyword Arguments:
        :param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
        :param str start_text: Text to start off the spinner with (default: {None})
        :param dict handler_map: Handler map for signals to be handled gracefully (default: {None})
        :param bool nospin: If true, use the dummy spinner (default: {False})
        :param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True)
        """

        self.handler = handler
        colorama.init()
        sigmap = {}  # type: TSignalMap
        if handler:
            sigmap.update({signal.SIGINT: handler, signal.SIGTERM: handler})
        handler_map = kwargs.pop("handler_map", {})
        if os.name == "nt":
            sigmap[signal.SIGBREAK] = handler
        else:
            sigmap[signal.SIGALRM] = handler
        if handler_map:
            sigmap.update(handler_map)
        spinner_name = kwargs.pop("spinner_name", "bouncingBar")
        start_text = kwargs.pop("start_text", None)
        _text = kwargs.pop("text", "Running...")
        kwargs["text"] = start_text if start_text is not None else _text
        kwargs["sigmap"] = sigmap
        kwargs["spinner"] = getattr(Spinners, spinner_name, "")
        write_to_stdout = kwargs.pop("write_to_stdout", True)
        self.stdout = kwargs.pop("stdout", sys.stdout)
        self.stderr = kwargs.pop("stderr", sys.stderr)
        self.out_buff = StringIO()
        self.write_to_stdout = write_to_stdout
        self.is_dummy = bool(yaspin is None)
        self._stop_spin = None  # type: Optional[threading.Event]
        self._hide_spin = None  # type: Optional[threading.Event]
        self._spin_thread = None  # type: Optional[threading.Thread]
        super(VistirSpinner, self).__init__(*args, **kwargs)
        if DISABLE_COLORS:
            colorama.deinit() 
Example #11
Source File: linter.py    From azure-cli-dev-tools with MIT License 4 votes vote down vote up
def run(self, run_params=None, run_commands=None, run_command_groups=None, run_help_files_entries=None):
        paths = import_module('{}.rules'.format(PACKAGE_NAME)).__path__

        if paths:
            ci_exclusions_path = os.path.join(paths[0], 'ci_exclusions.yml')
            self._ci_exclusions = yaml.safe_load(open(ci_exclusions_path)) or {}

        # find all defined rules and check for name conflicts
        found_rules = set()
        for _, name, _ in iter_modules(paths):
            rule_module = import_module('{}.rules.{}'.format(PACKAGE_NAME, name))
            functions = inspect.getmembers(rule_module, inspect.isfunction)
            for rule_name, add_to_linter_func in functions:
                if hasattr(add_to_linter_func, 'linter_rule'):
                    if rule_name in found_rules:
                        raise LinterError('Multiple rules found with the same name: %s' % rule_name)
                    found_rules.add(rule_name)
                    add_to_linter_func(self)

        colorama.init()
        # run all rule-checks
        if run_help_files_entries and self._rules.get('help_file_entries'):
            self._run_rules('help_file_entries')

        if run_command_groups and self._rules.get('command_groups'):
            self._run_rules('command_groups')

        if run_commands and self._rules.get('commands'):
            self._run_rules('commands')

        if run_params and self._rules.get('params'):
            self._run_rules('params')

        if not self.exit_code:
            print(os.linesep + 'No violations found.')

        if self._update_global_exclusion is not None:
            if self._update_global_exclusion == 'CLI':
                repo_paths = [get_cli_repo_path()]
            else:
                repo_paths = get_ext_repo_paths()
            exclusion_paths = [os.path.join(repo_path, 'linter_exclusions.yml') for repo_path in repo_paths]
            for exclusion_path in exclusion_paths:
                if not os.path.isfile(exclusion_path):
                    open(exclusion_path, 'a').close()
                exclusions = yaml.safe_load(open(exclusion_path)) or {}
                exclusions.update(self._violiations)
                yaml.safe_dump(exclusions, open(exclusion_path, 'w'))

        colorama.deinit()
        return self.exit_code