我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorama.init()。
def ex_print (type, msg, ret): colorama.init() # Define color and style constants c_error = Fore.RED c_action = Fore.YELLOW c_ok = Fore.GREEN c_white = Fore.WHITE s_br = Style.BRIGHT s_reset = Style.RESET_ALL message = { "error": c_error + s_br, "action": c_action, "positive": c_ok + s_br, "info": c_white + s_br, "reset": s_reset } style = message.get(type, s_reset) if ret == 0: print(style + msg, end = "") else: print(style + msg)
def test_pretty_output(): # Currently this is a graphical test -- you should show the output # using "-s" option in pytest and check it manually with your eyes. pprint = print_pretty colorama.init() print('normal print') pprint('wow wow wow!') print('just print') pprint('wow!') pprint('some long loading.... zzzzzzzzzzzzz', status=PrintStatus.WAITING) time.sleep(0.3) pprint('doing something...', status=PrintStatus.WAITING) time.sleep(0.3) pprint('done!', status=PrintStatus.DONE) pprint('doing something...', status=PrintStatus.WAITING) time.sleep(0.3) pprint('doing more...', status=PrintStatus.WAITING) time.sleep(0.3) pprint('failed!', status=PrintStatus.FAILED) print('normal print')
def _lazy_colorama_init(): """ Lazily init colorama if necessary, not to screw up stdout is debug not enabled. This version of the function does init colorama. """ global _inited if not _inited: # pytest resets the stream at the end - causes troubles. Since # after every output the stream is reset automatically we don't # need this. initialise.atexit_done = True try: init() except Exception: # Colorama fails with initializing under vim and is buggy in # version 0.3.6. pass _inited = True
def __init__(self, in_file = None): import sys self._line_wrap = False self._write_pos = 0 self._file = in_file or sys.stdout #self._file = sys.stdout if not (hasattr(self._file, 'isatty') and self._file.isatty()): # the stdout is not a terminal, this for example happens if the # output is piped to less, e.g. "bin/test | less". In this case, # the terminal control sequences would be printed verbatim, so # don't use any colors. self.write = self.normal_write elif sys.platform != "win32": # We are on *nix system we can use ansi self.write = self.ansi_write else: try: import colorama colorama.init(wrap=False) self._file = colorama.AnsiToWin32(self._file).stream self.write = self.ansi_write except ImportError: self.write = self.normal_write
def main(): # type: () -> typing.Any """Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message. """ colorama.init(wrap=six.PY3) doc = usage.get_primary_command_usage() allow_subcommands = '<command>' in doc args = docopt(doc, version=settings.version, options_first=allow_subcommands) if sys.excepthook is sys.__excepthook__: sys.excepthook = log.excepthook try: log.enable_logging(log.get_log_level(args)) default_args = sys.argv[2 if args.get('<command>') else 1:] if (args.get('<command>') == 'help' and None not in settings.subcommands): subcommand = next(iter(args.get('<args>', default_args)), None) return usage.get_help_usage(subcommand) argv = [args.get('<command>')] + args.get('<args>', default_args) return _run_command(argv) except exc.InvalidCliValueError as e: return str(e)
def init_io(self): if sys.platform not in {'win32', 'cli'}: return self.enable_win_unicode_console() import colorama colorama.init() # For some reason we make these wrappers around stdout/stderr. # For now, we need to reset them so all output gets coloured. # https://github.com/ipython/ipython/issues/8669 # io.std* are deprecated, but don't show our own deprecation warnings # during initialization of the deprecated API. with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) io.stdout = io.IOStream(sys.stdout) io.stderr = io.IOStream(sys.stderr)
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')
def configure_logging(config): logging.config.dictConfig(config) # By default the install() function installs a handler on the root logger, # this means that log messages from your code and log messages from the # libraries that you use will all show up on the terminal. coloredlogs.install(level=logging.DEBUG, fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%I:%S') logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING) if sys.stdout.isatty(): colorama.init(autoreset=True) else: # We're being piped, so skip colors colorama.init(strip=True)
def git_helper(self): self.addHost('daemon', 'host', 'http://localhost', 'user', 'pw', force = True) r1 = git.Repo.init('repo1') Path('repo1/deps.got').write_text("repo2\nrepo3\n") r1.index.add(['deps.got']) r1.index.commit('Commit') with GotRun(['--here', 'host:repo1', 'repo1', '--force']): pass r2 = git.Repo.init('repo2') r2.index.commit('Commit') with GotRun(['--here', 'host:repo2', 'repo2', '--force']): pass r3 = git.Repo.init('repo3') r3.index.commit('Commit') with GotRun(['--here', 'host:repo3', 'repo3', '--force']): pass return r1, r2, r3
def newGame(self): """ Load board with init conditions And sync virtual board """ self.board = np.array([[0]*self.size] * self.size, dtype=int) mL = int(self.board.shape[0]/2 - 1) mR = int(self.board.shape[0]/2) self.board[mL][mL] = 1 self.board[mR][mR] = 1 self.board[mR][mL] = -1 self.board[mL][mR] = -1 self.nextTurn = self.BLACK self.syncVirtualBoard() self.gameOver = False return
def main(): colorama.init() # gratuitous use of lambda. pos = lambda y, x: '\x1b[%d;%dH' % (y, x) # draw a white border. print(Back.WHITE, end='') print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='') for y in range(MINY, 1+MAXY): print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='') print('%s%s' % (pos(MAXY, MINX), ' '*MAXX), end='') # draw some blinky lights for a while. for i in range(PASSES): print('%s%s%s%s%s' % (pos(randint(1+MINY,MAXY-1), randint(1+MINX,MAXX-1)), choice(FORES), choice(BACKS), choice(STYLES), choice(CHARS)), end='') # put cursor to top, left, and set color to white-on-black with normal brightness. print('%s%s%s%s' % (pos(MINY, MINX), Fore.WHITE, Back.BLACK, Style.NORMAL), end='')
def main(): colorama.init(autoreset=True) parser = argparse.ArgumentParser() parser.add_argument('testfile', type=lambda x: is_valid_file_path(parser, x), help='Start with a Testfile') parser.add_argument('-v', '--validate', action='store_const', default=run_test, const=run_validation, dest='func', help='Validates Testfile') parser.add_argument('-m', '--iterations', type=int, default=None, help='Changes the number of iterations that nuts waits for a result') parser.add_argument('-r', '--retries', default=None, type=int, help='Set the max retries for failed tests') parser.add_argument('-c', '--config', type=lambda x: is_valid_file_path(parser, x), default=None, help='Config file formatted as YAML. Settings will be merged with ENVVARs') parser.add_argument('-d', '--debug', action='store_true', default=False, help='Debug mode vor STDOUT and log files.') args = parser.parse_args() load_settings(config_file=args.config, retries=args.retries, iterations=args.iterations, debug=args.debug) setup_logger() result = args.func(testfile=args.testfile) if not result: exit(1)
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()
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)
def upgrade_wpt_runner(self): env = self.build_env() with cd(path.join(self.context.topdir, 'tests', 'wpt', 'harness')): code = call(["git", "init"], env=env) if code: return code # No need to report an error if this fails, as it will for the first use call(["git", "remote", "rm", "upstream"], env=env) code = call( ["git", "remote", "add", "upstream", "https://github.com/w3c/wptrunner.git"], env=env) if code: return code code = call(["git", "fetch", "upstream"], env=env) if code: return code code = call(["git", "reset", "--hard", "remotes/upstream/master"], env=env) if code: return code code = call(["rm", "-rf", ".git"], env=env) if code: return code return 0
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()
def main(): """Handles command-line params and runs the respective core function.""" colorama.init(autoreset=True) args = docopt(__doc__, version="Foliant %s (Python)" % foliant_version) if args["build"] or args["make"]: result = builder.build(args["<target>"], args["--path"]) elif args["upload"] or args["up"]: result = uploader.upload(args["<document>"]) print("---") print(Fore.GREEN + "Result: %s" % result) colorama.deinit()
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)
def set_colors(): global G, Y, B, R, W , M , C , end if sys.platform.startswith('win'): # Windows deserve coloring too :D try: import win_unicode_console , colorama win_unicode_console.enable() colorama.init() #Now the unicode will work ^_^ G = '\033[92m' # green Y = '\033[93m' # yellow B = '\033[94m' # blue R = '\033[91m' # red W = '\033[0m' # white M = '\x1b[35m' # magenta C = '\x1b[36m' # cyan end = '\33[97m' except: #print("[!] Error: Coloring libraries not installed ,no coloring will be used [Check the readme]") G = Y = B = R = W = G = Y = B = R = W = '' else: G = '\033[92m' # green Y = '\033[93m' # yellow B = '\033[94m' # blue R = '\033[91m' # red W = '\033[0m' # white M = '\x1b[35m' # magenta C = '\x1b[36m' # cyan end = '\33[97m'
def init(): global organizer, repo, local_repo, downloader, qs downloader = Downloader(down_cache) handler = NexusHandler() downloader.add_handler(handler) handler = LoversLabHandler() downloader.add_handler(handler) organizer = MO(cfg) repo_dir = cfg.repo.dir if not repo_dir.exists(): repo_dir.makedirs() repo = GitRemotePackageRepo( organizer, repo_dir, cfg.repo.url ) local_dir = cfg.local.dir if not local_dir.exists(): local_dir.makedirs() local_repo = LocalPackageRepo(organizer, local_dir)
def remote(): init()
def local(): init()
def main(): colorama.init() import ai.backend.client.cli.config # noqa import ai.backend.client.cli.run # noqa import ai.backend.client.cli.proxy # noqa import ai.backend.client.cli.admin # noqa import ai.backend.client.cli.admin.keypairs # noqa import ai.backend.client.cli.admin.sessions # noqa import ai.backend.client.cli.admin.agents # noqa import ai.backend.client.cli.admin.vfolders # noqa import ai.backend.client.cli.vfolder # noqa import ai.backend.client.cli.ps # noqa if len(sys.argv) <= 1: global_argparser.print_help() return mode = Path(sys.argv[0]).stem if mode == '__main__': pass elif mode == 'lcc': sys.argv.insert(1, 'c') sys.argv.insert(1, 'run') elif mode == 'lpython': sys.argv.insert(1, 'python') sys.argv.insert(1, 'run') args = global_argparser.parse_args() if hasattr(args, 'function'): args.function(args) else: print_fail('The command is not specified or unrecognized.')
def _lazy_colorama_init(): """ Lazily init colorama if necessary, not to screw up stdout is debug not enabled. This version of the function does nothing. """ pass
def __init__(self): colorama.init() self.white = colorama.Fore.WHITE self.red = colorama.Fore.RED self.blue = colorama.Fore.BLUE self.green = colorama.Fore.GREEN self.yellow = colorama.Fore.YELLOW # yellow self.lightwhite = colorama.Fore.LIGHTWHITE_EX self.lightred = colorama.Fore.LIGHTRED_EX self.lightblue = colorama.Fore.LIGHTBLUE_EX self.lightgreen = colorama.Fore.LIGHTGREEN_EX self.lightyellow = colorama.Fore.LIGHTYELLOW_EX
def __init__(self, parent): """ NOTE: This could be implemented as decorators... """ self.parent = parent if COLORAMA: colorama.init(autoreset = True)
def _RunInternal(parser, output_directory=None): colorama.init() parser.set_defaults(output_directory=output_directory) from_wrapper_script = bool(output_directory) args = _ParseArgs(parser, from_wrapper_script) run_tests_helper.SetLogLevel(args.verbose_count) args.command.ProcessArgs(args) args.command.Run() # Incremental install depends on the cache being cleared when uninstalling. if args.command.name != 'uninstall': _SaveDeviceCaches(args.command.devices, output_directory) # TODO(agrieve): Remove =None from target_cpu on or after October 2017. # It exists only so that stale wrapper scripts continue to work.
def __init__(self): # `autoreset` allows us to not have to sent reset sequences for every # string. `strip` lets us preserve color when redirecting. colorama.init(autoreset=True, strip=False)
def _install_coreos(self, node_id, provision_config_id, network, password): self.info('Installing CoreOS...') # boot in to the provision configuration self.info('Booting into Provision configuration profile...') self.request('linode.boot', params={'LinodeID': node_id, 'ConfigID': provision_config_id}) # connect to the server via ssh ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) while True: try: ssh.connect(str(network['public']), username='root', password=password, allow_agent=False, look_for_keys=False) break except: continue # copy the cloud config self.info('Pushing cloud config...') cloud_config_template = string.Template(self._get_cloud_config()) cloud_config = cloud_config_template.safe_substitute(public_ipv4=network['public'], private_ipv4=network['private'], gateway=network['gateway'], hostname=network['hostname']) sftp = ssh.open_sftp() sftp.open('cloud-config.yaml', 'w').write(cloud_config) self.info('Installing...') commands = [ 'wget https://raw.githubusercontent.com/coreos/init/master/bin/coreos-install -O $HOME/coreos-install', 'chmod +x $HOME/coreos-install', '$HOME/coreos-install -d /dev/sdb -C ' + self.coreos_channel + ' -V ' + self.coreos_version + ' -c $HOME/cloud-config.yaml -t /dev/shm' ] for command in commands: stdin, stdout, stderr = ssh.exec_command(command) stdout.channel.recv_exit_status() print stdout.read() ssh.close()
def main(): colorama.init() parser = argparse.ArgumentParser(description='Apply a "Security Group" to a Deis cluster') parser.add_argument('--private-key', required=True, type=file, dest='private_key', help='Cluster SSH Private Key') parser.add_argument('--private', action='store_true', dest='private', help='Only allow access to the cluster from the private network') parser.add_argument('--discovery-url', dest='discovery_url', help='Etcd discovery url') parser.add_argument('--hosts', nargs='+', dest='hosts', help='The IP addresses of the hosts to apply rules to') args = parser.parse_args() nodes = get_nodes_from_args(args) hosts = args.hosts if args.hosts is not None else nodes node_ips = [] for ip in nodes: if validate_ip_address(ip): node_ips.append(ip) else: log_warning('Invalid IP will not be added to security group: ' + ip) if not len(node_ips) > 0: raise ValueError('No valid IP addresses in security group.') host_ips = [] for ip in hosts: if validate_ip_address(ip): host_ips.append(ip) else: log_warning('Host has invalid IP address: ' + ip) if not len(host_ips) > 0: raise ValueError('No valid host addresses.') log_info('Generating iptables rules...') rules = get_firewall_contents(node_ips, args.private) log_success('Generated rules:') log_debug(rules) log_info('Applying rules...') apply_rules_to_all(host_ips, rules, args.private_key) log_success('Done!')
def init_color(no_color: bool) -> None: global success_color, info_hl, info_color, warning_hl, warning_color, error_hl, error_color, highlight_color, \ color_reset if no_color: success_color = info_hl = info_color = warning_hl = warning_color = error_hl = error_color = highlight_color =\ color_reset = "" else: colorama.init()
def _colorama(*args, **kwargs): """Temporarily enable colorama.""" colorama.init(*args, **kwargs) try: yield finally: colorama.deinit()
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))
def showHelp(): if sys.platform=="win32": try: import colorama colorama.init() except: pass prefix=styles["prefix"](rsjoin(" ", ("python -m", endMainRx.sub("", __spec__.name)))) print( rsjoin("\n", ( styles["cli"](rsjoin(" ", (prefix, cliArg))) + styles["help"](" - "+par[1]) for cliArg, par in singleArgLUT.items() )) )
def main(): # colorama works cross-platform to color text output in CLI colorama.init() parser = argparse.ArgumentParser(description=''' aptos is a tool for validating client-submitted data using the JSON Schema vocabulary and converts JSON Schema documents into different data-interchange formats. ''', usage='%(prog)s [arguments] SCHEMA', epilog=''' More information on JSON Schema: http://json-schema.org/''') subparsers = parser.add_subparsers(title='Arguments') validation = subparsers.add_parser( 'validate', help='Validate a JSON instance') validation.add_argument( '-instance', type=str, default=json.dumps({}), help='JSON document being validated') validation.set_defaults(func=validate) conversion = subparsers.add_parser( 'convert', help=''' Convert a JSON Schema into a different data-interchange format''') conversion.add_argument( '-format', type=str, choices=['avro'], help='data-interchange format') conversion.set_defaults(func=convert) parser.add_argument( 'schema', type=str, help='JSON document containing the description') arguments = parser.parse_args() arguments.func(arguments)
def init(): pick_da_useragent() atexit.register(save_data) load_data()
def main(): init() run()
def initialize_git_repo(current): os.chdir(current) result = subprocess.Popen(['git', 'init'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) res1 = result.communicate()[0] subprocess.Popen(['git', 'add', '.'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() subprocess.Popen(['git', 'commit', '-m', 'First commit'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() subprocess.Popen(['git', 'tag', '-a', '0.1', '-m', 'First alpha version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() print(Fore.MAGENTA + " [+] " + str(res1, 'utf-8') + Fore.RESET)