本文整理汇总了Python中termcolor.cprint函数的典型用法代码示例。如果您正苦于以下问题:Python cprint函数的具体用法?Python cprint怎么用?Python cprint使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了cprint函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: svn_command
def svn_command(subcommand, *args):
command = ['svn', '--non-interactive']
# if not local_cache:
# command.append('--no-auth-cache')
command.append('--no-auth-cache')
if trust_cert:
command.append('--trust-server-cert')
command.append(subcommand)
if not verbose and subcommand not in ('info', 'cleanup'):
command.append('-q')
command.extend(args)
if verbose:
if '--username' in command or '--password' in command:
filtered_command = []
for i in range(len(command)):
# remove username and password from logging
user_pass = ('--username', '--password')
if command[i] in user_pass or \
(i > 0 and command[i - 1] in user_pass):
continue
filtered_command.append(command[i])
cprint('>>> ' + ' '.join(filtered_command), 'cyan')
else:
cprint('>>> ' + ' '.join(command), 'cyan')
if subprocess.call(command) != 0:
raise SVNError(subcommand)
示例2: print_path
def print_path(url):
resp = requests.get(url)
respjson= simplejson.loads(resp.text)
checkresp(respjson, resp)
keypoints = respjson['routes'][0]['legs'][0]
print "From: " + keypoints['start_address']
print "To: " + keypoints['end_address']
print "Distance: " + keypoints['distance']['text']
print "Duration: " + keypoints['duration']['text']
printwarnings(respjson)
if 'mode=transit' in url:
print keypoints['departure_time']['text'] + ' to ' + keypoints['arrival_time']['text']
steps, linenum = keypoints['steps'], 1
for step in steps:
instruction = sanitize(step['html_instructions'])
#fix for formatting issue on last line of instructions
instruction = re.sub('Destination', '. Destination', instruction)
sys.stdout.write(str(linenum) + '. ' + instruction + ': ')
cprint(step['duration']['text'], 'green')
linenum += 1
示例3: linecount
def linecount(self):
count = 0
for x in enumerate(self.file):
count = count + 1
message = 'Counting '+str(count)
cprint('\r%s' % message,'green',end='')
return count
示例4: fix
def fix(self):
"""clowder fix command"""
if self.clowder_repo is not None:
cprint('Fix...\n', 'yellow')
self.clowder.fix_version(self.args.version)
else:
exit_clowder_not_found()
示例5: _run_action
def _run_action(args):
defaulted_components = False
components = settings.parse_components(args.pop("components"))
if not components:
defaulted_components = True
components = _get_def_components()
action = _clean_action(args.pop("action"))
if not action:
cprint("No valid action specified!", "red")
return False
rootdir = args.pop("dir")
if rootdir is None:
cprint("No root directory specified!", "red")
return False
#ensure os/distro is known
(distro, platform) = utils.determine_distro()
if distro is None:
print("Unsupported platform " + colored(platform, "red") + "!")
return False
#start it
(rep, maxlen) = utils.welcome(_WELCOME_MAP.get(action))
header = utils.center_text("Action Runner", rep, maxlen)
print(header)
#need to figure out dependencies for components (if any)
ignore_deps = args.pop('ignore_deps', False)
if not defaulted_components:
LOG.info("Activating components [%s]" % (", ".join(sorted(components.keys()))))
else:
LOG.info("Activating default components [%s]" % (", ".join(sorted(components.keys()))))
if not ignore_deps:
new_components = settings.resolve_dependencies(components.keys())
component_diff = new_components.difference(components.keys())
if component_diff:
LOG.info("Having to activate dependent components: [%s]" % (", ".join(sorted(component_diff))))
for new_component in component_diff:
components[new_component] = list()
component_skips = _check_roots(action, rootdir, components.keys())
for c in component_skips:
components.pop(c)
if not components:
LOG.error("After checking the various components roots, no components ended up being specified!")
return False
#get the right component order (by priority)
component_order = settings.prioritize_components(components.keys())
if action in _REVERSE_ACTIONS:
#reverse them so that we stop in the reverse order
#and that we uninstall in the reverse order which seems to make sense
component_order.reverse()
#add in any that will just be referenced but which will not actually do anything (ie the action will not be applied to these)
ref_components = settings.parse_components(args.pop("ref_components"))
for c in ref_components.keys():
if c not in components:
components[c] = ref_components.get(c)
#now do it!
LOG.info("Starting action [%s] on %s for distro [%s]" % (action, date.rcf8222date(), distro))
results = _run_components(action, component_order, components, distro, rootdir, args)
LOG.info("Finished action [%s] on %s" % (action, date.rcf8222date()))
if results:
LOG.info('Check [%s] for traces of what happened.' % ", ".join(results))
return True
示例6: validate_users
def validate_users(self):
self.app.log.debug('Validating GitHub account names.')
# validate required config parameters
if not self.app.config.get('github', 'auth_token') or not self.app.config.get('github', 'auth_id'):
raise error.ConfigError("Missing config parameter 'github.auth_id' and/or 'github.auth_token'! "
"Please run 'scrum-tools github authorize' first! ")
key_username = self.app.config.get('core', 'users_schema_key_username')
key_github = self.app.config.get('core', 'users_schema_key_github')
user_repository = data.UserRepository(self.app.config)
gh = login(token=self.app.config.get('github', 'auth_token'))
for u in user_repository.users():
if not u[key_github]:
cprint("Skipping empty GitHub account for user '%s'." % u[key_username], 'yellow', file=sys.stdout)
continue
print colored("Validating GitHub account '%s' for user '%s'..." % (u[key_github], u[key_username]), 'green'),
try:
if gh.user(u[key_github]):
print colored('OK', 'green', attrs=['bold'])
else:
raise RuntimeError("Github user '%s' not found" % u[key_github])
except RuntimeError:
print colored('Not OK', 'red', attrs=['bold'])
示例7: moveEpisodeDir
def moveEpisodeDir(self, dname, possibleShowName):
source = os.path.join(self.SortConfig.TvDir, dname)
target = os.path.join(self.SortConfig.TvDir, possibleShowName)
shutil.move(source, target)
cprint('Moved ' + dname + ' to ' + target, 'red')
self.fixSymlink(dname, target)
示例8: wiki_geosearch
def wiki_geosearch(option, opt_str, value, parser):
"""
used to find out what happend at a certain location or in the range of radius
"""
length = len(parser.rargs)
global geosearch_res
[latitude, longtitude, radius] = [0] * 3
if length < 2:
parser.error(colored("option -g needs at least 2 arguments!", "red", attrs=["bold"]))
elif length > 3:
parser.error(colored("option -g can't handle more than 3 arguments!", "red", attrs=["bold"]))
elif length == 2:
[latitude, longtitude] = parser.rargs[:]
else:
[latitude, longtitude, radius] = parser.rargs[:]
try:
geosearch_res = geosearch(latitude, longtitude, radius=radius)
except WikipediaException:
parser.error(
colored(
"An unknown error occured: 'Invalid coordinate provided'. Please report it on GitHub!",
"red",
attrs=["bold"],
)
)
exit(1)
for res in geosearch_res:
cprint(res + "\n", "green")
示例9: test_stop
def test_stop(stop_name):
"""Run a series of tests on the command-line for the given stop name."""
# Make sure we don't have more than one consecutive blank in the stop name.
stop_name = re.sub(" +", " ", stop_name)
# Use ' ' in strings below to allow single blanks in stop names.
examples = """
--help
--stop %(stop_name)s
--stop %(stop_name)s --header
--stop %(stop_name)s --tablefmt rst
--stop %(stop_name)s --num-line-groups 2
--stop %(stop_name)s --num-line-groups 2 --filter-line U
""" % {
"stop_name": stop_name.encode("utf-8")
}
# --stop Bahnhof --header --filter-name "(Potsdam)" # fails
examples = examples.strip().split("\n")
for example in examples:
prog = join(os.getcwd(), sys.argv[0])
cmd = "%s %s %s" % (sys.executable, prog, example.strip())
termcolor.cprint(cmd, attrs=["bold"]) ## todo:
print("")
subprocess.check_call(cmd.decode("utf-8").split(" "))
print("")
示例10: affiche_grille
def affiche_grille(grille, largeur, longueur):
global printed_pause
global pause
###Bouge le curseur au dessus et affiche score ###
cprint("\033[;H Score: {} ".format(score.value), 'white', 'on_cyan', ['bold'])
# on utilise "\033[;H" pour remettre le curseur au dessus car la commande "clear" est trop lente
# => overwrite
### Affichage matrice ###
border = colored('+', 'yellow', 'on_yellow')
print(border * (longueur * 2 + 4))
for i in range(largeur):
print(border * 2, end="")
for j in range (longueur):
print(grille[i][j], end=grille[i][j])
print(border * 2)
print(border * (longueur * 2 + 4))
## Si c'est finit ou pausé
if game_over.value == True:
print("Game Over")
print("Réessayez ?[o/n]\n")
if pause.value == True and printed_pause.value == False:
print("Paused")
printed_pause.value = True
else:
print(" ") ### Pour cacher le mot "Paused" => overwrite
示例11: PrintMainUI
def PrintMainUI():
text = colored("Task List", "grey", "on_white")
print ">" * 10 + text + "<" * 10
print "\n1. Settings"
print "2. Data Management"
print "3. Machine Control"
cprint("4. Quit\n", "magenta")
示例12: _TCP_multiple
def _TCP_multiple(self):
try:
mysock = create_tcp_socket(self.to,'conn')
try:
with self.lock:
self.c+=1
d=mysock.connect_ex((self.tgt,self.port))
if d == 0:
with self.lock:
self.c+=1
serv = getportserv(self.port)
if self.quite == True:
data=(str(self.port),'open',serv)
p.put(data)
else:
print str(self.port).ljust(7)+'open'.ljust(7)+serv
except KeyboardInterrupt:
sys.exit(cprint('[-] Canceled by user','red'))
finally:
pass
except KeyboardInterrupt:
sys.exit(cprint('[-] Canceled by user','red'))
except:
pass
finally:
pass
示例13: help_print
def help_print(self):
"""Display the docstrings for all commands"""
for command in self.commands.items():
termcolor.cprint(command[0], attrs=['bold'])
print(" " + command[1].__doc__ + '\n')
self.titlebar = "Showing documentation"
return len(self.commands)*3
示例14: make_url
def make_url(parser, options, args, printInfo=True):
checkinput(options)
url_end = ''
for key,value in options.__dict__.items():
if(value != None):
if key in ["departure_time", "arrival_time"]:
try:
value = int(value)
except ValueError as e:
value = int(mktime(cal.parse(value)[0]))
finally:
time = value
value = str(value)
if not (isinstance(value, bool) or isinstance(value, int)):
re.sub(' ', '+', value)
url_end += key + '=' + value + '&'
origin = re.sub(' ', '+', args[1])
destination = re.sub(' ', '+', args[2])
if not options.nourl :
cprint (_("To view these directions online, follow this link: ") + "http://mapof.it/" + origin + '/' + destination, 'cyan')
base_url = 'http://maps.googleapis.com/maps/api/directions/json?origin=' + origin + '&destination=' + destination + '&'
url = (base_url + url_end)[:-1]
while True:
val =print_path(url,printInfo,options.mode , int(options.width))
if val > 0:
return val
示例15: initiateHandshake
def initiateHandshake(self):
cprint('ASKING FOR: HANDSHAKE to %s:%s'
%(self.transport.getPeer().host, self.transport.getPeer().port),
'cyan', 'on_blue', attrs=['bold'])
def replyArrived(reply):
cprint('RECEIVED: HANDSHAKE REPLY. \n%s' %(reply), 'cyan', 'on_blue')
print('\n')
ip = self.transport.getPeer().host
d = Mercury.checkIfNodeExists(reply['NodeId'])
def processNode(nodeExists):
if nodeExists:
return Mercury.updateAndGetNode(reply['NodeId'], ip, reply['ListeningPort'])
# This returns deferred
else:
return Mercury.createNode(reply['NodeId'], ip, reply['ListeningPort'])
d.addCallback(processNode)
d.addCallback(self.setGlobalConnectedNode) # This is at one level up, directly below protocol class.
d.addCallback(self.requestHeaders)
d.addCallback(self.requestNodes)
self.callRemote(networkAPI.Handshake,
NodeId=self.factory.localNodeId,
ListeningPort=aetherListeningPort,
ProtocolVersion=protocolVersion)\
.addCallback(replyArrived)\
.addErrback(self.closeConnection, 'OUTBOUND', self.initiateHandshake.__name__)