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)
python类init()的实例源码
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 _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_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 _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 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 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():
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 _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, 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 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 _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 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 _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_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 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()