Python colorama.init() Examples

The following are 30 code examples of colorama.init(). 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: subbrute.py    From AttackSurfaceMapper with GNU General Public License v3.0 6 votes vote down vote up
def cprint(type, msg, reset):
    colorama.init()
    message = {
        "action": Fore.YELLOW,
        "positive": Fore.GREEN + Style.BRIGHT,
        "info": Fore.YELLOW,
        "reset": Style.RESET_ALL,
        "red": Fore.RED,
        "white": Fore.WHITE,
        "green": Fore.GREEN,
        "yellow": Fore.YELLOW
    }
    style = message.get(type.lower())


# A resolver wrapper around dnslib.py 
Example #2
Source File: worker.py    From ray-legacy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_function_on_all_workers(self, function):
    """Run arbitrary code on all of the workers.

    This function will first be run on the driver, and then it will be exported
    to all of the workers to be run. It will also be run on any new workers that
    register later. If ray.init has not been called yet, then cache the function
    and export it later.

    Args:
      function (Callable): The function to run on all of the workers. It should
        not take any arguments. If it returns anything, its return values will
        not be used.
    """
    if self.mode not in [None, raylib.SCRIPT_MODE, raylib.SILENT_MODE, raylib.PYTHON_MODE]:
      raise Exception("run_function_on_all_workers can only be called on a driver.")
    # First run the function on the driver.
    function(self)
    # If ray.init has not been called yet, then cache the function and export it
    # when connect is called. Otherwise, run the function on all workers.
    if self.mode is None:
      self.cached_functions_to_run.append(function)
    else:
      self.export_function_to_run_on_all_workers(function) 
Example #3
Source File: worker.py    From ray-legacy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_mode(self, mode):
    """Set the mode of the worker.

    The mode SCRIPT_MODE should be used if this Worker is a driver that is being
    run as a Python script or interactively in a shell. It will print
    information about task failures.

    The mode WORKER_MODE should be used if this Worker is not a driver. It will
    not print information about tasks.

    The mode PYTHON_MODE should be used if this Worker is a driver and if you
    want to run the driver in a manner equivalent to serial Python for debugging
    purposes. It will not send remote function calls to the scheduler and will
    insead execute them in a blocking fashion.

    The mode SILENT_MODE should be used only during testing. It does not print
    any information about errors because some of the tests intentionally fail.

    args:
      mode: One of SCRIPT_MODE, WORKER_MODE, PYTHON_MODE, and SILENT_MODE.
    """
    self.mode = mode
    colorama.init() 
Example #4
Source File: cli.py    From practNLPTools-lite with MIT License 6 votes vote down vote up
def user_test(
    senna_path="",
    sent="",
    dep_model="",
    batch=False,
    stp_dir="",
    init=False,
    env=False,
    env_path="",
):

    if init:

        download_files()

    main(senna_path, sent, dep_model, batch, stp_dir) 
Example #5
Source File: __init__.py    From python-cli-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def message(
    *tokens: Token,
    end: str = "\n",
    sep: str = " ",
    fileobj: FileObj = sys.stdout,
    update_title: bool = False
) -> None:
    """ Helper method for error, warning, info, debug

    """
    if using_colorama():
        global _INITIALIZED
        if not _INITIALIZED:
            colorama.init()
            _INITIALIZED = True
    with_color, without_color = process_tokens(tokens, end=end, sep=sep)
    if CONFIG["record"]:
        _MESSAGES.append(without_color)
    if update_title and with_color:
        write_title_string(without_color, fileobj)
    to_write = with_color if config_color(fileobj) else without_color
    write_and_flush(fileobj, to_write) 
Example #6
Source File: logger.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_logger(log_requests=False):
    """ Initialize the logger """

    logger = logging.getLogger(__name__.split(".")[0])
    for handler in logger.handlers:  # pragma: no cover
        logger.removeHandler(handler)

    if os.name == "nt" and "colorama" in sys.modules:  # pragma: no cover
        colorama.init()

    formatter = coloredlogs.ColoredFormatter(fmt="%(asctime)s: %(message)s")
    handler = logging.StreamHandler(stream=sys.stdout)
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    logger.propagate = False

    if log_requests:
        requests.packages.urllib3.add_stderr_logger() 
Example #7
Source File: search4.py    From Search4 with GNU General Public License v3.0 6 votes vote down vote up
def main():
    link_data = parse_yaml()
    colorama.init()
    start_time = datetime.now()
    banner()
    user_name = parse_args()
    if not user_name:
        print_usage()
        exit(1)
    print_username(user_name)
    print_delimiter()

    for group, data in link_data.items():
        print_title(group)
        threads = []
        for site, url in data.items():
            t = Thread(target=run_thread, args=[url, site, user_name])
            t.start()
            threads.append(t)
        [th.join() for th in threads]
        print_separator()

    complete_time = datetime.now() - start_time
    print_exec_time(complete_time)
    print_finish() 
Example #8
Source File: subhunter.py    From AttackSurfaceMapper with GNU General Public License v3.0 6 votes vote down vote up
def cprint(type, msg, reset):
    colorama.init()
    message = {
        "action": Fore.YELLOW,
        "positive": Fore.GREEN + Style.BRIGHT,
        "info": Fore.YELLOW,
        "reset": Style.RESET_ALL,
        "red": Fore.RED,
        "white": Fore.WHITE,
        "green": Fore.GREEN,
        "yellow": Fore.YELLOW
    }
    style = message.get(type.lower())

    if type == "error":
        print("{0}\n[*] Error: {1}".format(Fore.RED + Style.BRIGHT, Style.RESET_ALL + Fore.WHITE + msg))
    else:
        print(style + msg, end="")
    if (reset == 1):
        print(Style.RESET_ALL) 
Example #9
Source File: __init__.py    From lightnovel-crawler with Apache License 2.0 6 votes vote down vote up
def start_app():
    init()

    check_updates()
    cancel_method()

    try:
        bot = os.getenv('BOT', '').lower()
        run_bot(bot)
    except Exception as err:
        if os.getenv('debug_mode') == 'yes':
            raise err
        else:
            error_message(err)
        # end if
    # end try

    epilog()

    # if Icons.isWindows and get_args().suppress is False:
    #     input('Press ENTER to exit...')
    # # end if
# end def 
Example #10
Source File: mpfshell.py    From mpfshell with MIT License 6 votes vote down vote up
def __init__(self, color=False, caching=False, reset=False):
        if color:
            colorama.init()
            cmd.Cmd.__init__(self, stdout=colorama.initialise.wrapped_stdout)
        else:
            cmd.Cmd.__init__(self)

        if platform.system() == "Windows":
            self.use_rawinput = False

        self.color = color
        self.caching = caching
        self.reset = reset

        self.fe = None
        self.repl = None
        self.tokenizer = Tokenizer()

        self.__intro()
        self.__set_prompt_path() 
Example #11
Source File: run.py    From examples with MIT License 6 votes vote down vote up
def ensure_cache_preserved():
    cache_directory = os.environ["CONAN_USER_HOME"]

    git = Git(folder=cache_directory)
    with open(os.path.join(cache_directory, '.gitignore'), 'w') as gitignore:
        gitignore.write(".conan/data/")
    git.run("init .")
    git.run("add .")

    try:
        yield
    finally:
        r = git.run("diff")
        if r:
            writeln_console(">>> " + colorama.Fore.RED + "This is example modifies the cache!")
            writeln_console(r)
            raise Exception("Example modifies cache!") 
Example #12
Source File: bin.py    From tcex with Apache License 2.0 6 votes vote down vote up
def __init__(self, _args):
        """Initialize Class properties.

        Args:
            _args (namespace): The argparser args Namespace.
        """
        self.args = _args

        # properties
        self.app_path = os.getcwd()
        self.exit_code = 0
        self.ij = InstallJson()
        self.lj = LayoutJson()
        self.permutations = Permutations()
        self.tj = TcexJson()

        # initialize colorama
        c.init(autoreset=True, strip=False) 
Example #13
Source File: buckethunter.py    From AttackSurfaceMapper with GNU General Public License v3.0 6 votes vote down vote up
def cprint(type, msg, reset):
    colorama.init()
    message = {
        "action": Fore.YELLOW,
        "positive": Fore.GREEN + Style.BRIGHT,
        "info": Fore.YELLOW,
        "reset": Style.RESET_ALL,
        "red": Fore.RED,
        "white": Fore.WHITE,
        "green": Fore.GREEN,
        "yellow": Fore.YELLOW
    }
    style = message.get(type.lower())

    if type == "error":
        print("{0}\n[*] Error: {1}".format(Fore.RED + Style.BRIGHT, Style.RESET_ALL + Fore.WHITE + msg))
    else:
        print(style + msg, end="")
    if (reset == 1):
        print(Style.RESET_ALL) 
Example #14
Source File: asm.py    From AttackSurfaceMapper with GNU General Public License v3.0 6 votes vote down vote up
def cprint(type, msg, reset):
    colorama.init()
    message = {
        "action": Fore.YELLOW,
        "positive": Fore.GREEN + Style.BRIGHT,
        "info": Fore.YELLOW,
        "reset": Style.RESET_ALL,
        "red": Fore.RED,
        "white": Fore.WHITE,
        "green": Fore.GREEN,
        "yellow": Fore.YELLOW
    }
    style = message.get(type.lower())

    if type == "error":
        print("{0}\n[*] Error: {1}".format(Fore.RED + Style.BRIGHT, Style.RESET_ALL + Fore.WHITE + msg))
    else:
        print(style + msg, end="")
    if reset == 1:
        print(Style.RESET_ALL)


# Print Results Function - 
Example #15
Source File: netdev-async.py    From network-programmability-stream with MIT License 6 votes vote down vote up
def main() -> None:
    colorama.init()
    start_time = datetime.now()
    loop = asyncio.get_event_loop()

    tasks = [
        loop.create_task(get_outputs(host_info, COMMANDS))
        for host_info in HOSTS.items()
    ]

    loop.run_until_complete(asyncio.wait(tasks))

    for hostname, task in zip(HOSTS, tasks):
        outputs = task.result()
        print(f"Device {hostname}")
        for command, output in zip(COMMANDS, outputs):
            print(f"===== Output from command {command} =====")
            print(f"{output}\n")
        print(f"=" * 80)

    exec_time = (datetime.now() - start_time).total_seconds()
    print(colorama.Fore.GREEN + f"Summary: it took {exec_time:,.2f} seconds to run") 
Example #16
Source File: Commands.py    From kobo-book-downloader with The Unlicense 6 votes vote down vote up
def ListBooks( listAll: bool ) -> None:
		colorama.init()

		rows = Commands.__GetBookList( listAll )
		for columns in rows:
			revisionId = colorama.Style.DIM + columns[ 0 ] + colorama.Style.RESET_ALL
			title = colorama.Style.BRIGHT + columns[ 1 ] + colorama.Style.RESET_ALL

			author = columns[ 2 ]
			if len( author ) > 0:
				title += " by " + author

			archived = columns[ 3 ]
			if archived:
				title += colorama.Fore.LIGHTYELLOW_EX + " (archived)" + colorama.Fore.RESET

			print( "%s \t %s" % ( revisionId, title ) ) 
Example #17
Source File: core.py    From shellpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def exe(cmd, params):
    """This function runs after preprocessing of code. It actually executes commands with subprocess

    :param cmd: command to be executed with subprocess
    :param params: parameters passed before ` character, i.e. p`echo 1 which means print result of execution
    :return: result of execution. It may be either Result or InteractiveResult
    """

    global _colorama_intialized
    if _is_colorama_enabled() and not _colorama_intialized:
        _colorama_intialized = True
        colorama.init()

    if config.PRINT_ALL_COMMANDS:
        if _is_colorama_enabled():
            _print_stdout(Fore.GREEN + '>>> ' + cmd + Style.RESET_ALL)
        else:
            _print_stdout('>>> ' + cmd)

    if _is_param_set(params, _PARAM_INTERACTIVE):
        return _create_interactive_result(cmd, params)
    else:
        return _create_result(cmd, params) 
Example #18
Source File: output.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def __init__(self, **kwargs):
        """Setup the initial set of output stream functions."""

        # Begins intercepting output and converting ANSI characters to win32 as applicable
        colorama.init()

        # Refactor this as an Output class
        self.__dict__['redirectErr'] = OutputRedirect(sys.stderr, self.handlePrint, LOG_TYPES[Level.VERBOSE])
        self.__dict__['redirectOut'] = OutputRedirect(sys.stdout, self.handlePrint, LOG_TYPES[Level.VERBOSE])

        # by default, dont steal output and print to console
        self.stealStdio(False)
        self.logToConsole(True)

        # Setattr wraps the output objects in a
        # decorator that allows this class to intercept their output, This dict holds the
        # original objects.
        self.__dict__['outputMappings'] = {}

        for name, func in six.iteritems(kwargs):
            setattr(self, name, func) 
Example #19
Source File: logger.py    From cloudify-cli with Apache License 2.0 6 votes vote down vote up
def configure_loggers():
    # first off, configure defaults
    # to enable the use of the logger
    # even before the init was executed.
    logger_config = copy.deepcopy(LOGGER)
    _configure_defaults(logger_config)

    if env.is_initialized():
        # init was already called
        # use the configuration file.
        _configure_from_file(logger_config)
    _set_loggers_verbosity(logger_config)
    logging.config.dictConfig(logger_config)

    global _lgr
    _lgr = logging.getLogger('cloudify.cli.main')

    # configuring events/logs loggers
    # (this will also affect local workflow loggers, which don't use
    # the get_events_logger method of this module)
    if is_use_colors():
        logs.EVENT_CLASS = ColorfulEvent
        # refactor this elsewhere if colorama is further used in CLI
        colorama.init(autoreset=True) 
Example #20
Source File: pokecli.py    From OpenPoGoBot with MIT License 6 votes vote down vote up
def main():
    # log settings
    # log format
    # logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    colorama.init()

    config_dir = init_config()
    if not config_dir:
        return

    kernel.set_config_file(config_dir)
    kernel.boot()

    try:
        bot = kernel.container.get('pokemongo_bot')
        bot.start()

        while True:
            bot.run()

    except KeyboardInterrupt:
        logger = kernel.container.get('logger')
        logger.log('[x] Exiting PokemonGo Bot', 'red') 
Example #21
Source File: isolateserver.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _prepare(self):
    h = self._algo()
    total = 0
    for chunk in self.content():
      h.update(chunk)
      total += len(chunk)
    # pylint: disable=attribute-defined-outside-init
    # This is not true, they are defined in Item.__init__().
    self._digest = h.hexdigest()
    self._size = total
    self._meta = {
      'h': self.digest,
      's': self.size,
      't': u'tar',
    } 
Example #22
Source File: hq_main.py    From HackQ-Trivia with MIT License 5 votes vote down vote up
def __init__(self):
        HackQ.download_nltk_resources()
        colorama.init()

        self.bearer = config.get("CONNECTION", "BEARER")
        self.timeout = config.getfloat("CONNECTION", "Timeout")
        self.show_next_info = config.getboolean("MAIN", "ShowNextShowInfo")
        self.exit_if_offline = config.getboolean("MAIN", "ExitIfShowOffline")
        self.show_bearer_info = config.getboolean("MAIN", "ShowBearerInfo")
        self.headers = {"User-Agent": "Android/1.40.0",
                        "x-hq-client": "Android/1.40.0",
                        "x-hq-country": "US",
                        "x-hq-lang": "en",
                        "x-hq-timezone": "America/New_York",
                        "Authorization": f"Bearer {self.bearer}",
                        "Connection": "close"}

        self.session = requests.Session()
        self.session.headers.update(self.headers)

        self.init_root_logger()
        self.logger = logging.getLogger(__name__)

        # Find local UTC offset
        now = time.time()
        self.local_utc_offset = datetime.fromtimestamp(now) - datetime.utcfromtimestamp(now)

        self.validate_bearer()
        self.logger.info("HackQ-Trivia initialized.\n", extra={"pre": colorama.Fore.GREEN}) 
Example #23
Source File: universal.py    From azure-devops-cli-extension with MIT License 5 votes vote down vote up
def publish_package(feed,
                    name,
                    version,
                    path,
                    description=None,
                    scope='organization',
                    organization=None,
                    project=None,
                    detect=None):
    """Publish a package to a feed.
    :param scope: Scope of the feed: 'project' if the feed was created in a project, and 'organization' otherwise.
    :type scope: str
    :param feed: Name or ID of the feed.
    :type feed: str
    :param name: Name of the package, e.g. 'foo-package'.
    :type name: str
    :param version: Version of the package, e.g. '1.0.0'.
    :type version: str
    :param description: Description of the package.
    :type description: str
    :param path: Directory containing the package contents.
    :type path: str
    """
    colorama.init()   # Needed for humanfriendly spinner to display correctly

    if scope == 'project':
        organization, project = resolve_instance_and_project(
            detect=detect,
            organization=organization,
            project=project)
    else:
        if project is not None:
            raise CLIError('--scope \'project\' is required when specifying a value in --project')

        organization = resolve_instance(
            detect=detect,
            organization=organization)

    artifact_tool = ArtifactToolInvoker(ProgressReportingExternalToolInvoker(), ArtifactToolUpdater())
    return artifact_tool.publish_universal(organization, project, feed, name, version, description, path) 
Example #24
Source File: worker.py    From ray-legacy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cleanup(worker=global_worker):
  """Disconnect the driver, and terminate any processes started in init.

  This will automatically run at the end when a Python process that uses Ray
  exits. It is ok to run this twice in a row. Note that we manually call
  services.cleanup() in the tests because we need to start and stop many
  clusters in the tests, but the import and exit only happen once.
  """
  disconnect(worker)
  worker.set_mode(None)
  services.cleanup() 
Example #25
Source File: __init__.py    From python-cli-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def config_color(fileobj: FileObj) -> bool:
    if CONFIG["color"] == "never":
        return False
    if CONFIG["color"] == "always":
        return True
    if os.name == "nt":
        # sys.isatty() is False on mintty, so
        # let there be colors by default. (when running on windows,
        # people can use --color=never)
        # Note that on Windows, when run from cmd.exe,
        # console.init() does the right thing if sys.stdout is redirected
        return True
    else:
        return fileobj.isatty() 
Example #26
Source File: worker.py    From ray-legacy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_connected(worker=global_worker):
  """Check if the worker is connected.

  Raises:
    Exception: An exception is raised if the worker is not connected.
  """
  if worker.handle is None and worker.mode != raylib.PYTHON_MODE:
    raise RayConnectionError("This command cannot be called before a Ray cluster has been started. You can start one with 'ray.init(start_ray_local=True, num_workers=1)'.") 
Example #27
Source File: worker.py    From ray-legacy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __setattr__(self, name, value):
    """Set an attribute. This handles reusable variables as a special case.

    This is used to create reusable variables. When it is called, it runs the
    function for initializing the variable to create the variable. If this is
    called on the driver, then the functions for initializing and reinitializing
    the variable are shipped to the workers.

    If this is called before ray.init has been run, then the reusable variable
    will be cached and it will be created and exported when connect is called.

    Args:
      name (str): The name of the attribute to set. This is either a whitelisted
        name or it is treated as the name of a reusable variable.
      value: If name is a whitelisted name, then value can be any value. If name
        is the name of a reusable variable, then this is a Reusable object.
    """
    try:
      slots = self._slots
    except AttributeError:
      slots = ()
    if slots == ():
      return object.__setattr__(self, name, value)
    if name in slots:
      return object.__setattr__(self, name, value)
    reusable = value
    if not issubclass(type(reusable), Reusable):
      raise Exception("To set a reusable variable, you must pass in a Reusable object")
    # Create the reusable variable locally, and export it if possible.
    self._create_and_export(name, reusable)
    # Create an empty attribute with the name of the reusable variable. This
    # allows the Python interpreter to do tab complete properly.
    return object.__setattr__(self, name, None) 
Example #28
Source File: worker.py    From ray-legacy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _create_and_export(self, name, reusable):
    """Create a reusable variable and add export it to the workers.

    If ray.init has not been called yet, then store the reusable variable and
    export it later then connect is called.

    Args:
      name (str): The name of the reusable variable.
      reusable (Reusable): The reusable object to use to create the reusable
        variable.
    """
    self._names.add(name)
    self._reinitializers[name] = reusable.reinitializer
    # Export the reusable variable to the workers if we are on the driver. If
    # ray.init has not been called yet, then cache the reusable variable to
    # export later.
    if _mode() in [raylib.SCRIPT_MODE, raylib.SILENT_MODE]:
      _export_reusable_variable(name, reusable)
    elif _mode() is None:
      self._cached_reusables.append((name, reusable))
    self._reusables[name] = reusable.initializer()
    # We create a second copy of the reusable variable on the driver to use
    # inside of remote functions that run locally. This occurs when we start Ray
    # in PYTHON_MODE and when  we call a remote function locally.
    if _mode() in [raylib.SCRIPT_MODE, raylib.SILENT_MODE, raylib.PYTHON_MODE]:
      self._local_mode_reusables[name] = reusable.initializer() 
Example #29
Source File: __init__.py    From pysslscan with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self):
        if colorama_init:
            colorama_init(autoreset=False)
            self.colors = {
                "RESET": Fore.RESET,
                "BLACK": Fore.BLACK,
                "RED": Fore.RED,
                "GREEN": Fore.GREEN,
                "YELLOW": Fore.YELLOW,
                "BLUE": Fore.BLUE,
                "MAGENTA": Fore.MAGENTA,
                "CYAN": Fore.CYAN
                #"GRAY": Fore.GRAY
            }
        else:
            CSI = "\33["
            self.CSI = CSI
            self.colors = {
                "RESET": CSI + "0m",
                "BLACK": CSI + "0;30m",
                "RED": CSI + "0;31m",
                "GREEN": CSI + "0;32m",
                "YELLOW": CSI + "0;33m",
                "BLUE": CSI + "0;34m",
                "MAGENTA": CSI + "0;35m",
                "CYAN": CSI + "0;36m"
                #"GRAY": CSI + "0;37m"
            }

        self.mapped_colors = {}
        self.mapped_colors["default"] = {
            "DANGER": "RED",
            "ERROR": "RED",
            "OK": "GREEN",
            "SUCCESS": "GREEN",
            "WARNING": "YELLOW"
        } 
Example #30
Source File: cli.py    From python-blueprint with MIT License 5 votes vote down vote up
def main() -> ExitStatus:
    """Accept arguments from the user, compute the factorial, and display the results."""
    colorama.init(autoreset=True, strip=False)
    args = parse_args()

    print(
        f"fact({colorama.Fore.CYAN}{args.n}{colorama.Fore.RESET}) = "
        f"{colorama.Fore.GREEN}{factorial(args.n)}{colorama.Fore.RESET}"
    )
    return ExitStatus.success


# Allow the script to be run standalone (useful during development in PyCharm).