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类WHITE的实例源码
def display_warning_to_user(self):
""" display warning to user
show user the commands + switches and ask if they
would still like to proceed or not """
user_message = Fore.CYAN + "\nYou are about to run the following commands:"
print(user_message)
for command in self.commands:
print(command)
user_message = Fore.CYAN + "\nOn the following devices:"
print(user_message)
for device in sorted(self.devices.keys()):
print(device)
user_message = Fore.RED + "\nAre you sure you wish to proceed? (y/n) " + Fore.WHITE
user_input = input(user_message)
if user_input.lower() == 'y':
return True
else:
return False
def banner():
print(Style.DIM)
print(' ___________________________')
print(' / /\\')
print(' / sadboyzvone\'s _/ /\\')
print(' / Intel 8080 / \/')
print(' / Assembler /\\')
print('/___________________________/ /')
print('\___________________________\/')
print(' \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\'
+ Style.RESET_ALL + Style.BRIGHT)
print(Fore.WHITE + '\nPowered by ' + Fore.BLUE + 'Pyt'
+ Fore.YELLOW + 'hon' + Fore.WHITE
+ '\nCopyright (C) 2017, Zvonimir Rudinski')
# Print usage information
def load_url(url, timeout):
# Build URL query to email signup page
urlquery = "http://" + url + "/m-users-a-email_list-job-add-email-" + targetEmail + "-source-2.htm"
print_out(Style.BRIGHT + Fore.WHITE + "Sending request to: " + url)
# Build the request
req = urllib.request.Request(
urlquery,
data=None,
headers={
'User-Agent': random.choice(useragents),
'Host': url
}
)
# Send
try:
f = urllib.request.urlopen(req)
print_out(Style.BRIGHT + Fore.GREEN + "Successfully sent!")
f.close()
except urllib.error.URLError as e:
print_out(Style.BRIGHT + Fore.RED + e.reason)
def printBoard(self):
"""
Print board to terminal for debugging
"""
def getItem(item):
if item == Board.BLACK :
return Fore.WHITE + "|" + Fore.BLACK + "O"
elif item == Board.WHITE :
return Fore.WHITE + "|" + Fore.WHITE + "O"
else:
return Fore.WHITE + "| "
def getRow(row):
return "".join(map(getItem,row))
print("\t" + Back.GREEN + " BOARD ")
print("\t" + Back.GREEN + Fore.WHITE + " |0|1|2|3|4|5|6|7")
for i in range(8):
print("\t" + Back.GREEN + Fore.WHITE + "{}{}".format(i,
getRow(self.board[i])))
sys.stdout.write(Style.RESET_ALL)
def printBoard(self, t='live'):
"""
Print board to terminal for debugging
@param string type 'virtual' or 'live'
"""
board = self.board if t == 'live' else self.virtualBoard
print(Back.GREEN + "\t BOARD ")
# Print column titles
head = Back.GREEN + Fore.WHITE + "\t "
for i in range(self.board.shape[0]):
head += '|' + str(i)
print(head)
# Print rows
for i in range(self.board.shape[0]):
print(Back.GREEN + Fore.WHITE + "\t" + str(i) + getRow(board[i]))
print(Style.RESET_ALL)
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 getparam(ser, p_name, p_data):
"""Decode a specific parameter from the serial port."""
printc(Back.RED + p_name, prepend='\n')
for typ in p_data:
schr = ser.read()
if typ == 'h':
printc(c2hex(schr), Fore.GREEN)
elif typ == 'H':
if len(HIGHLIGHT):
HIGHLIGHT.popleft()
HIGHLIGHT.append(c2hex(schr))
printc(c2hex(schr), Fore.BLUE)
elif typ == 'a':
printc(c2ascii(schr) or c2hex(schr), Fore.WHITE, prepend='')
else:
printc(c2hex(schr), Fore.WHITE)
printc(Style.RESET_ALL, prepend='')
def menu():
# Using colour from colorama: https://pypi.python.org/pypi/colorama
# Formatting e.g.: Fore.COLOUR, Back.COLOUR, Style.DIM with e.g. DIM, RED, CYAN, etc.:
print(Fore.BLACK + Back.WHITE + "10cbazbt3 menu:" + Style.RESET_ALL)
print(Fore.YELLOW + Style.DIM + "Main:")
print(" b = Blurb m = Mentions")
print(" r = Reply t = Timeline")
print(" blog = BLOG o = Own blurbs")
print(" pins = PINS")
print("Admin:")
print(" Login = Login menu = show Menu")
print(" Logout = Logout. sites = my Sites")
print(" exit = Exit")
print(Style.RESET_ALL)
# DEFINE 10C POST INTERACTIONS:
# LOTS OF DUPLICATION HERE!
# Define the 'blurb' (social post) subroutine:
def show_options(require):
#print Back.WHITE + Fore.WHITE + "Module parameters" + Style.RESET_ALL
for line in require:
if require[line][0]["value"] == "":
value = "No value"
else:
value = require[line][0]["value"]
if require[line][0]["required"] == "yes":
if require[line][0]["value"] != "":
print Fore.GREEN+Style.BRIGHT+ "+ " +Style.RESET_ALL+line+ ": " +value
else:
print Fore.RED+Style.BRIGHT+ "- " +Style.RESET_ALL+line+ "(" +Fore.RED+ "is_required" +Style.RESET_ALL+ "):" +value
else:
if require[line][0]["value"] != "":
print Fore.GREEN+Style.BRIGHT+ "+ " +Style.RESET_ALL+line + ": " +value
else:
print Fore.WHITE+Style.BRIGHT+ "* " +Style.RESET_ALL+line + "(" +Fore.GREEN+ "optional" +Style.RESET_ALL+ "):" +value
#print Back.WHITE + Fore.WHITE + "End parameters" + Style.RESET_ALL
def print_and_log(to_print, level='info', logger=None, display=True):
if display:
if level == 'default':
for line in to_print:
print Fore.WHITE + line + '\r'
if level == 'info':
print_info(to_print)
elif level == 'error':
print_error(to_print)
if logger is not None:
write_to_logger(logger, to_print, level)
sys.stdout.flush()
def printHelp():
print('\nThis ' + Fore.BLUE + 'Intel' + Fore.WHITE
+ ' 8080 assembler was made for ' + Fore.BLUE + 'Project '
+ Fore.YELLOW + 'Week' + Fore.WHITE + ' at my school.')
print('It is written in ' + Fore.BLUE + 'Pyt' + Fore.YELLOW + 'hon'
+ Fore.WHITE)
print('Modules: ' + Fore.RED + 'Co' + Fore.BLUE + 'lo'
+ Fore.YELLOW + 'ra' + Fore.GREEN + 'ma' + Fore.WHITE)
print('\nPass a file path as an arguement.')
# Main function
def color_row(row):
color = Fore.WHITE
label = "."
if u'label' in row:
color = LABEL_COLOR.get(row[u'label'], Fore.WHITE)
label = row[u'label']
row[u'label'] = "%s%s%s" % (color, label, Style.RESET_ALL)
row['family'] = "%s%s%s" % (color, row.get('family', "."), Style.RESET_ALL)
row['size'] = smart_size(row.get(u'size', "."))
return row
def m_fatal(self, m):
m = '[X] ' + m
if COLORAMA:
print Fore.WHITE + Back.RED + m
else:
print m
def m_fatal(self, m):
m = '[X] ' + m
if COLORAMA:
print Fore.WHITE + Back.RED + m
else:
print m
def m_fatal(self, m):
m = '[X] ' + m
if COLORAMA:
print Fore.WHITE + Back.RED + m
else:
print m
def print_major_alarms(mj):
"""
Args:
mj (int): Counts of major alarms
Returns:
str: Colorized information by using colorama
"""
if mj > 0:
return Back.RED + Fore.WHITE + str(mj) + Fore.RESET + Back.RESET
else:
return Fore.GREEN + str(mj) + Fore.RESET
def run_plugin( plugin ):
start = time.time()
print '[-] Start {}'.format( plugin[1] )
with open( devnull, 'w' ) as FNULL:
subprocess.call( plugin, stdout=FNULL )
#end = '[+] Ends {0:<20}: {:.2f}s'.format( plugin[1], time.time() - start )
end = '{:.2f}s'.format( time.time() - start )
print (Fore.WHITE + '[+]') , 'Ends {:25}--> {}'.format( plugin[1], end )
return
def present_synonyms(synonym_groups, query):
table = defaultdict(list)
for sg in sorted(synonym_groups.keys()):
synonyms = synonym_groups[sg]
table[sg] = [COLORS[category - 1] + word
for category in sorted(synonyms.keys(), reverse=True)
for word in sorted(synonyms[category])]
table[sg].append(Fore.WHITE + "")
print ">> Results from searching: %s, where the first row denotes the context of where the synonyms are used.\n" % query
print tabulate(table, tablefmt="rst", headers="keys")
def __str__(self):
ign = ' (ignoring any extra subfields)' if self.ignore_extra_subfields else ''
args = (Fore.WHITE + six.text_type(self.source) + Style.RESET_ALL,
Fore.WHITE + six.text_type(self.target) + Style.RESET_ALL,
ign)
return 'Replace `{}` ? `{}`{}'.format(*args)
def _run(self, marc_record):
print()
time.sleep(1)
print('{}{}: {}{}'.format(Fore.WHITE, marc_record.id, marc_record.title(), Style.RESET_ALL).encode('utf-8'))
for field in marc_record.fields:
if field.tag.startswith('6'):
if field.sf('2') == self.source.sf['2']:
if field.match(self.source):
print(' > {}{}{}'.format(Fore.YELLOW, field, Style.RESET_ALL).encode('utf-8'))
else:
print(' {}{}{}'.format(Fore.YELLOW, field, Style.RESET_ALL).encode('utf-8'))
else:
print(' {}'.format(field).encode('utf-8'))
while True:
targets = pick('Make a selection (or press Ctrl-C to abort)', self.targets, OrderedDict((
('REMOVE', 'None of them (remove the field)'),
)))
if 'REMOVE' in targets and len(targets) > 1:
log.warning('Invalid selection. Please try again or press Ctrl-C to abort.')
else:
break
if len(targets) == 0:
log.info('Skipping this record')
return 0
tasks = []
if 'REMOVE' in targets:
tasks.append(DeleteTask(self.source, ignore_extra_subfields=self.ignore_extra_subfields))
else:
tasks.append(ReplaceTask(self.source, targets[0], ignore_extra_subfields=self.ignore_extra_subfields))
for target in targets[1:]:
tasks.append(AddTask(target))
modified = 0
for task in tasks:
modified += task.run(marc_record)
return modified
def __str__(self):
return 'List titles having `{}`'.format(Fore.WHITE + six.text_type(self.source) + Style.RESET_ALL)
def __str__(self):
return 'Delete `{}`'.format(Fore.WHITE + six.text_type(self.source) + Style.RESET_ALL)
def __str__(self):
return 'Add `{}`'.format(Fore.WHITE + six.text_type(self.target) + Style.RESET_ALL)
def color_green(text):
return Fore.GREEN+text+Fore.WHITE
# JSON validator function
def screen_data(self, defrag=False):
status = self.status
text = Fore.WHITE
text += term.bold('Pyflix\n\n')
text += STATES[status.state]
text += term.yellow(' %.2f%% complete ' % (status.progress * 100))
rates = self.rates()
rate_text = '(down: %.1f kB/s up: %.1f kB/s peers: %d)\n' % \
(rates[0], rates[1], status.num_peers)
text += term.green(rate_text)
if defrag:
text += self.defrag()
text += Fore.WHITE
text += "\n\n"
if self._video_file is not None:
text += term.white("Serving ")
text += term.yellow(self.video_file[0])
text += term.white(" on ")
text += term.blue("http://localhost:%s\n") % self.port
text += term.white("Elapsed Time: ")
text += term.red(self.elapsed_time())
text += "\n"
return text
ProfilePicConverter.py 文件源码
项目:vanilla-nodebb-importer
作者: Linux-statt-Windows
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def log(text):
print(Fore.GREEN + '==> ' + Fore.WHITE + text)
ProfilePicConverter.py 文件源码
项目:vanilla-nodebb-importer
作者: Linux-statt-Windows
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def log_warn(text):
print(Fore.YELLOW + '==> Warning: ' + Fore.WHITE + text)
ProfilePicConverter.py 文件源码
项目:vanilla-nodebb-importer
作者: Linux-statt-Windows
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def log_err(text):
print(Fore.RED + '==> Error: ' + Fore.WHITE + text)
# NOTE: If you use this script as module, call this function!
def TOR_CHECK_PRNT(data):
if (data["IsTor"]==True):
print ("[" + Fore.GREEN + Style.BRIGHT + "+" + Style.RESET_ALL + "]" + Fore.GREEN + Style.BRIGHT + " TorStat's network traffic was routed through tor, onto the next stage...\n" + Style.RESET_ALL)
return True
elif (data["IsTor"]==False):
print ("[" + Fore.YELLOW + Style.BRIGHT + "!" + Style.RESET_ALL + "]" + Fore.YELLOW + Style.BRIGHT +" TorStat cannot perform any more recon on the tor servers because TorStat's network traffic was not routed through tor.\n\t " + Style.RESET_ALL + Fore.WHITE + Style.DIM + "=> try : proxychains python TorStat.py\n" + Style.RESET_ALL)
return False