本文整理汇总了Python中termcolor.cprint函数的典型用法代码示例。如果您正苦于以下问题:Python cprint函数的具体用法?Python cprint怎么用?Python cprint使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了cprint函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:zhuzhuor,项目名称:saedeploy,代码行数:29,代码来源:saedeploy.py
示例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
开发者ID:salemtalha,项目名称:googmaps,代码行数:25,代码来源:map.py
示例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
开发者ID:ArchaicSmile,项目名称:circles,代码行数:7,代码来源:ntParser.py
示例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()
开发者ID:CambrianTech,项目名称:clowder-1,代码行数:7,代码来源:cmd.py
示例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
开发者ID:DJHartley,项目名称:Openstack-Devstack2,代码行数:60,代码来源:actions.py
示例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'])
开发者ID:aalexandrov,项目名称:scrum-tools,代码行数:28,代码来源:github.py
示例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)
开发者ID:crazyquark,项目名称:pysortinghat,代码行数:7,代码来源:cleaner.py
示例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")
开发者ID:forblackking,项目名称:wiki_terminal,代码行数:30,代码来源:wiki_functions.py
示例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("")
开发者ID:pfigue,项目名称:vbbvg,代码行数:27,代码来源:vbbvg.py
示例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
开发者ID:roscale,项目名称:snake,代码行数:31,代码来源:snake.py
示例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")
开发者ID:yuehuang1108,项目名称:AutoProcessing,代码行数:7,代码来源:Main.py
示例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
开发者ID:t7hm1,项目名称:collector,代码行数:28,代码来源:connscan.py
示例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
开发者ID:BinkyToo,项目名称:PIMesh,代码行数:7,代码来源:cliui.py
示例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
开发者ID:wilzbach,项目名称:googmaps,代码行数:33,代码来源:map.py
示例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__)
开发者ID:Ryman,项目名称:aether-public,代码行数:27,代码来源:aetherProtocol.py
示例16: configure
def configure(self,data):
try:
def keys(data):
call(['touch',data['home_dir']+'/.ssh/authorized_keys'])
call(['chmod','600',data['home_dir']+'/.ssh/authorized_keys'])
call(['touch',data['home_dir']+'/.ssh/id_rsa'])
call(['chmod','400',data['home_dir']+'/.ssh/id_rsa'])
def permission(data):
call(['chmod','-R','700',data['home_dir']+'/.ssh'])
def ownership(data):
call(['chown','-R',data['name']+':'+data['name'],data['home_dir']+'/.ssh'])
def settings(data):
call(['touch',data['home_dir']+'/.ssh/config'])
config_path = data['home_dir']+'/.ssh/config'
if os.path.isfile(config_path):
config_file = open(config_path,'wt')
config_file.write('Host *\n\tStrictHostKeyChecking no\n')
config_file.close()
ssh_dir = call(['mkdir',data['home_dir']+'/.ssh'])
if ssh_dir!=0:
raise
permission(data)
keys(data)
settings(data)
ownership(data)
except Exception as Error:
self.remove(data)
cprint('Error configuring Identity.','red')
sys.exit(1)
开发者ID:abhijitmoha17,项目名称:slen-utils,代码行数:33,代码来源:identity.py
示例17: respondToHandshake
def respondToHandshake(self, NodeId, ListeningPort, ProtocolVersion):
ip = self.transport.getPeer().host
d = Mercury.checkIfNodeExists(NodeId)
def processNode(nodeExists):
if nodeExists:
return Mercury.updateAndGetNode(NodeId, ip, ListeningPort) # This returns deferred
else:
return Mercury.createNode(NodeId, ip, ListeningPort)
d.addCallback(processNode)
def callReverseSync(node):
# I'm going to ask for nodes in parallel with already existing header call.
d = self.requestHeaders(node)
d.addCallback(self.requestNodes)
return node
d.addCallback(callReverseSync)\
.addErrback(self.closeConnection, 'INBOUND', callReverseSync.__name__)
d.addCallback(self.setGlobalConnectedNode) # This is at one level up, directly below protocol class.
reply = {'NodeId': self.factory.localNodeId,
'ListeningPort': aetherListeningPort,
'ProtocolVersion': protocolVersion }
cprint('FROM REMOTE: HANDSHAKE REQUEST: from %s:%s'
%(ip, ListeningPort), 'white', 'on_yellow', attrs=['bold'])
cprint('ANSWER: %s' %(reply), 'white', 'on_yellow')
print('\n')
return reply
开发者ID:Ryman,项目名称:aether-public,代码行数:30,代码来源:aetherProtocol.py
示例18: display_cell
def display_cell(cell, agents):
# display height
if cell['color'] is not NONE_COLOR:
if cell['h']<0:
cprint('%d\t\t' % cell['h'], cell['color'], end='')
if cell['h']==0:
cprint(' %d\t\t' % cell['h'], cell['color'], end='')
return
if cell['h'] < 0:
# hole
print('%d' % cell['h']),
elif cell['h'] == 0:
# tile
print(' %d' % cell['h']),
else:
# obstacle
print(' #'),
#display tiles
if cell['tiles']:
for tile in cell['tiles']:
cprint('*', tile, end='')
# display agent
for agent in agents:
if agent.x == cell['x'] and agent.y == cell['y']:
cprint(',%d$' % agent.points, agent.color, end='')
if agent.carry_tile:
cprint('* ', agent.carry_tile, end='')
print('\t\t'),
开发者ID:dianatatu,项目名称:TileWorld,代码行数:28,代码来源:utils.py
示例19: git_create_repo
def git_create_repo(url, repo_path, remote, ref, depth=0):
"""Clone git repo from url at path"""
if not os.path.isdir(os.path.join(repo_path, '.git')):
if not os.path.isdir(repo_path):
os.makedirs(repo_path)
repo_path_output = colored(repo_path, 'cyan')
try:
print(' - Clone repo at ' + repo_path_output)
Repo.init(repo_path)
except:
cprint(' - Failed to initialize repository', 'red')
print('')
shutil.rmtree(repo_path)
sys.exit(1)
else:
repo = _repo(repo_path)
remote_names = [r.name for r in repo.remotes]
remote_output = colored(remote, 'yellow')
if remote not in remote_names:
try:
print(" - Create remote " + remote_output)
repo.create_remote(remote, url)
except:
message = colored(" - Failed to create remote ", 'red')
print(message + remote_output)
print('')
shutil.rmtree(repo_path)
sys.exit(1)
_checkout_ref(repo_path, ref, remote, depth)
开发者ID:JrGoodle,项目名称:clowder,代码行数:29,代码来源:git_utilities.py
示例20: importScoresByNames
def importScoresByNames(self, scores, assessmentId = 0, exactGradesourceNames = False):
if assessmentId == 0:
assessmentId = self.chooseAssessment()
GsNameToStudentId, postData = self.parseScoresForm(assessmentId)
utils.check("Gradesource name -> studentId: ", GsNameToStudentId)
errors = False
if not exactGradesourceNames:
ExtNameToGsName = self.matchNames(scores.keys(), GsNameToStudentId.keys())
for extName, GsName in ExtNameToGsName.items():
postData[GsNameToStudentId[GsName]] = scores[extName]
else:
for GsName, score in scores.items():
if GsName in GsNameToStudentId:
postData[GsNameToStudentId[GsName]] = score
else:
cprint('Missing name: ' + GsName, 'white', 'on_red')
errors = True
if errors:
sys.exit()
utils.check("Data to post: ", postData)
self.postScores(postData)
cprint("Go to %s" % (self.assessmentUrl % assessmentId), 'yellow')
开发者ID:qpleple,项目名称:moodle-gradesource,代码行数:26,代码来源:gradesource.py
注:本文中的termcolor.cprint函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论