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: output.py From Paradrop with Apache License 2.0 | 6 votes |
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 #2
Source File: core.py From shellpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #3
Source File: netdev-async.py From network-programmability-stream with MIT License | 6 votes |
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 #4
Source File: bin.py From tcex with Apache License 2.0 | 6 votes |
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 #5
Source File: mpfshell.py From mpfshell with MIT License | 6 votes |
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 #6
Source File: cli.py From practNLPTools-lite with MIT License | 6 votes |
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 #7
Source File: subhunter.py From AttackSurfaceMapper with GNU General Public License v3.0 | 6 votes |
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 #8
Source File: subbrute.py From AttackSurfaceMapper with GNU General Public License v3.0 | 6 votes |
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 #9
Source File: buckethunter.py From AttackSurfaceMapper with GNU General Public License v3.0 | 6 votes |
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 #10
Source File: asm.py From AttackSurfaceMapper with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: logger.py From cloudify-cli with Apache License 2.0 | 6 votes |
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 #12
Source File: worker.py From ray-legacy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #13
Source File: worker.py From ray-legacy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #14
Source File: __init__.py From python-cli-ui with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #15
Source File: logger.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #16
Source File: search4.py From Search4 with GNU General Public License v3.0 | 6 votes |
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 #17
Source File: __init__.py From lightnovel-crawler with Apache License 2.0 | 6 votes |
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 #18
Source File: run.py From examples with MIT License | 6 votes |
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 #19
Source File: Commands.py From kobo-book-downloader with The Unlicense | 6 votes |
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 #20
Source File: pokecli.py From OpenPoGoBot with MIT License | 6 votes |
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: my_data.py From ICDAR-2019-SROIE with MIT License | 5 votes |
def color_print(text, text_class): colorama.init() for c, n in zip(text, text_class): if n == 1: print(Fore.RED + c, end="") elif n == 2: print(Fore.GREEN + c, end="") elif n == 3: print(Fore.BLUE + c, end="") elif n == 4: print(Fore.YELLOW + c, end="") else: print(Fore.WHITE + c, end="") print(Fore.RESET) print()
Example #22
Source File: textmodetrees.py From udapi-python with GNU General Public License v3.0 | 5 votes |
def before_process_document(self, document): """Initialize ANSI colors if color is True or 'auto'. If color=='auto', detect if sys.stdout is interactive (terminal, not redirected to a file). """ super().before_process_document(document) if self.color == 'auto': self.color = sys.stdout.isatty() if self.color: colorama.init() if self.print_doc_meta: for key, value in sorted(document.meta.items()): print('%s = %s' % (key, value))
Example #23
Source File: logSetup.py From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, level=logging.DEBUG): UnlockedHandler.__init__(self, level) self.formatter = logging.Formatter('\r%(name)s - %(style)s%(levelname)s - %(message)s'+clr.Style.RESET_ALL) clr.init() self.logPaths = {}
Example #24
Source File: cloudfail.py From CloudFail with MIT License | 5 votes |
def init(target): if args.target: print_out(Fore.CYAN + "Fetching initial information from: " + args.target + "...") else: print_out(Fore.RED + "No target set, exiting") sys.exit(1) if not os.path.isfile("data/ipout"): print_out(Fore.CYAN + "No ipout file found, fetching data") update() print_out(Fore.CYAN + "ipout file created") try: ip = socket.gethostbyname(args.target) except socket.gaierror: print_out(Fore.RED + "Domain is not valid, exiting") sys.exit(0) print_out(Fore.CYAN + "Server IP: " + ip) print_out(Fore.CYAN + "Testing if " + args.target + " is on the Cloudflare network...") try: ifIpIsWithin = inCloudFlare(ip) if ifIpIsWithin: print_out(Style.BRIGHT + Fore.GREEN + args.target + " is part of the Cloudflare network!") else: print_out(Fore.RED + args.target + " is not part of the Cloudflare network, quitting...") sys.exit(0) except ValueError: print_out(Fore.RED + "IP address does not appear to be within Cloudflare range, shutting down..") sys.exit(0)
Example #25
Source File: restconf-async.py From network-programmability-stream with MIT License | 5 votes |
def main() -> None: colorama.init() start_time = datetime.now() loop = asyncio.get_event_loop() hostname_tasks = [ loop.create_task(get_hostname(host)) for host in HOSTS ] interface_tasks = [ loop.create_task(get_interfaces(host)) for host in HOSTS ] loop.run_until_complete(asyncio.gather(*hostname_tasks, *interface_tasks)) for host, hostname_task, interface_task in zip(HOSTS, hostname_tasks, interface_tasks): hostname = hostname_task.result() interfaces = interface_task.result() print(f"Device {host}") print(f"Hostname: {hostname}") print(f"Has interfaces:") for interface in interfaces: print(f" Interface {interface['name']} has ip address: {interface['ip_address']}") print(f"=" * 80) # print(f"Device {host} has hostname: {hostname}") exec_time = (datetime.now() - start_time).total_seconds() print(colorama.Fore.GREEN + f"Summary: it took {exec_time:,.2f} seconds to run")
Example #26
Source File: http-requests-async.py From network-programmability-stream with MIT License | 5 votes |
def main() -> None: colorama.init() start_time = datetime.now() loop = asyncio.get_event_loop() loop.run_until_complete(download_all_page_titles(URLS, loop)) exec_time = (datetime.now() - start_time).total_seconds() print(colorama.Fore.GREEN + f"Summary: it took {exec_time:,.2f} seconds to run")
Example #27
Source File: http-requests-async2.py From network-programmability-stream with MIT License | 5 votes |
def main() -> None: colorama.init() start_time = datetime.now() loop = asyncio.get_event_loop() tasks = [ loop.create_task(download_page_title(url)) for url in URLS ] loop.run_until_complete(asyncio.wait(tasks)) for url, task in zip(URLS, tasks): title = task.result() print(f"Web page {url} has title: {title}") exec_time = (datetime.now() - start_time).total_seconds() print(colorama.Fore.GREEN + f"Summary: it took {exec_time:,.2f} seconds to run")
Example #28
Source File: http-requests-threads.py From network-programmability-stream with MIT License | 5 votes |
def main() -> None: colorama.init() start_time = datetime.now() for url, title in zip(URLS, download_all_page_titles(URLS)): print(f"Web page {url} has title: {title}") exec_time = (datetime.now() - start_time).total_seconds() print(colorama.Fore.GREEN + f"Summary: it took {exec_time:,.2f} seconds to run")
Example #29
Source File: profile.py From tcex with Apache License 2.0 | 5 votes |
def init(self): """Return the Data (dict) from the current profile.""" if self.data is None: self.log.error('Profile init failed; loaded profile data is None') # Now can initialize anything that needs initializing self.session_init() # initialize session recording/playback if self.test_options: if self.test_options.get('autostage', False): self.init_autostage()
Example #30
Source File: utils.py From captcha-harvester with MIT License | 5 votes |
def __init__(self): colorama.init()