def annotated_source(sourcefile, marks=None, annotations=None, context=3, mark='*'): marks = marks or [] annotations = annotations or {} interresting = set(marks) | set(annotations) printed = [range(n - context, n + context + 1) for n in interresting] printed = set(sum(printed, [])) lastprinted = 0 with codecs.open(sourcefile, 'r', 'utf-8', 'replace') as f: print yellow(sourcefile) for n, line in enumerate(f, 1): if n in printed: m = red(mark if n in marks else ' ' * len(mark)) c = line.rstrip().expandtabs() if n in marks: c = red(c) if n in annotations: a = yellow('# ' + annotations[n]) else: a = '' print ' %4i %s %-80s %s' % (n, m, c, a) lastprinted = n elif lastprinted == n - 1: print bold(black(' %4s' % ('.' * len(str(n))))) else: pass
def diff_all_table_data(self): failures = 0 print(bold(red('Starting table analysis.'))) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) tables = sorted( self.firstinspector.get_table_names(schema="public")) for table in tables: if table in self.exclude_tables: print(bold(yellow(f"Ignoring table {table}"))) continue with Halo(text=f"Analysing table {table}. " f"[{tables.index(table) + 1}/{len(tables)}]", spinner='dots') as spinner: result, message = self.diff_table_data(table) if result is True: spinner.succeed(f"{table} - {message}") elif result is None: spinner.warn(f"{table} - {message}") else: failures += 1 spinner.fail(f"{table} - {message}") print(bold(green('Table analysis complete.'))) if failures > 0: return 1 return 0
def current_position(): """Where am I now?""" print(bold("You are at:")) print(bold("===========")) position = nimbus.travel.current_position() print("Place: {}".format(position["location"])) print("Latitude: {:.4f}".format(position["lat"])) print("Longitude: {:.4f}".format(position["lon"])) print("Stationary: {}".format(position["stationary"]))
def pcapopen(fn = None): from pcap import pcapObject p = pcapObject() try: if fn: p.open_offline(fn) else: p.open_live('any' , 200, False, 100) p.dispatch(-1,cb) except Exception as e: print bold(red('error:')),red(str(e)) pass
def run_as_hook(filename, commitA=None, commitB=None, skip=False): """ Runs in "hook" mode, called solely by git. filename: str commitA: str commitB: str skip: bool commitA and commitB exist /solely/ for profiling and testing """ # Initialize new repo (called from git hook so this directory works) repo = git.Repo('.') if commitA is not None and commitB is not None: previous_commit = repo.commit(commitB) current_commit = repo.commit(commitA) else: previous_commit = repo.commit('HEAD~1') current_commit = repo.commit('HEAD') # Get specific changes in each file todos = [] potential_todos = [] for filediff in previous_commit.diff(current_commit, create_patch=True): # Find all modified lines in file for line in str(filediff).split('\n'): if re.match('^\+', line) and re.match('^\+\+\+', line) is None: clean_line = re.sub('^\+ *', '', line) if check_is_todo(clean_line): todos.append((filediff.b_path, clean_line)) elif check_is_potential_todo(clean_line): potential_todos.append((filediff.b_path, clean_line)) if todos: print(color.bold(color.yellow( "Here's a list of TODOs you added in this commit:\n" "------------------------------------------------"))) with open(filename, 'a') as todofile: for todo in todos: print('+ {} | {}'.format(*todo)) check_date_and_save(todofile, todo[0], todo[1]) if potential_todos: # TODO: test print(color.bold(color.yellow( "These might be TODOs. Did you mean to do them?\n" "-----------------------------------------------"))) with open(filename, 'a') as todofile: for todo in potential_todos: if skip: choice = 'n' else: choice = input('+ {} | {} (y/N) '.format(*todo)) if choice.lower() == 'y': check_date_and_save(todofile, todo[0], todo[1]) print('')
def run_as_hook(filename, commitA=None, commitB=None): """ Runs in "hook" mode, called solely by git. filename: str commitA: str commitB: str commitA and commitB exist /solely/ for profiling and testing """ # Initialize new repo (called from git hook so this directory works) repo = git.Repo('.') if commitA is not None and commitB is not None: previous_commit = repo.commit(commitB) current_commit = repo.commit(commitA) else: previous_commit = repo.commit('HEAD~1') current_commit = repo.commit('HEAD') # Get specific changes in each file todos = [] potential_todos = [] for filediff in previous_commit.diff(current_commit, create_patch=True): # Find all modified lines in file for line in str(filediff).split('\n'): if re.match('^\+', line) and re.match('^\+\+\+', line) is None: clean_line = re.sub('^\+ *', '', line) if check_is_todo(clean_line): todos.append((filediff.b_path, clean_line)) elif check_is_potential_todo(clean_line): potential_todos.append((filediff.b_path, clean_line)) if todos: print( color.bold( color.yellow( "Here's a list of TODOs you added in this commit:\n" "------------------------------------------------"))) for todo in todos: print('+ {} | {}'.format(*todo)) check_date_and_save(filename, todo[0], todo[1]) if potential_todos: print( color.bold( color.yellow( "\n" "These might be TODOs. Did you mean to do them?\n" "-----------------------------------------------"))) for todo in potential_todos: print('+ {} | {}'.format(*todo)) check_date_and_save(filename, todo[0], todo[1]) print('')
def diff_all_sequences(self): print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) for sequence in sequences: with Halo(text=f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]", spinner='dots') as spinner: result, message = self.diff_sequence(sequence) if result is True: spinner.succeed(f"{sequence} - {message}") elif result is None: spinner.warn(f"{sequence} - {message}") else: spinner.fail(f"{sequence} - {message}") print(bold(green('Sequence analysis complete.')))
def get_result(self, results=None, index=0): """Returns a terminal representation of a YouTube Video result.""" if results is None: results = self.results try: vid = pafy.new(results[index]) except Exception: return str(index + 1) + ") This video is not available.\n" string = "" string += str(index + 1) + ") " string += str(color.bold(color.underline(vid.title))) + "\n" more_info = "Time: {} | Rating: {:.2f} | Views: {:,}\n" string += more_info.format(vid.duration, vid.rating, vid.viewcount) utils.term.bgcolor = 'white' thumbnail = requests.get(vid.thumb) image = fi.Image(StringIO(thumbnail.content)) width = min(utils.term.width, self.MAX_WIDTH) image.resize(width) string += textwrap.fill(vid.description[:500] + "...", width) + "\n" string += str(image) string += "/"*width + "\n" return string
def diff_all_sequences(self): print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) failures = 0 for sequence in sequences: status_update = StatusUpdate( f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]") result, message = self.diff_sequence(sequence) status_update.complete(result, f"{sequence} - {message}") if result is False: failures += 1 print(bold(green('Sequence analysis complete.'))) if failures > 0: return 1 return 0
def day(date): """What was yesterday like? Due to perculiarities, this only works after midday. TODO(robert) set the correct file so it works whenever. """ if date is None: filename = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime( config["tracking"]["historic_data_file"]) else: filename = datetime.datetime.strptime(date, "%Y-%m-%d").strftime( config["tracking"]["historic_data_file"]) info = gpx_trip.extract_info(open(filename).read(), predefined_stops=config["places"]) print(" " * 90, end="\r") for trip in info["trips"]: print(bold("Trip")) print( info["stops"][trip["from"]]["short_name"], "-", info["stops"][trip["to"]]["short_name"], ) print("{} - {}".format(trip["start"].strftime("%H:%M"), trip["end"].strftime("%H:%M"))) print() print(info)
def printTree(self, padding='', last=False, maxdepth=3, maxcount=50): """Print tree contained in file. Parameters ---------- padding : string Arguements passed in command line. last : boolean Last node in sequence maxdepth : number Limit dept maxcount : number Limit count """ if maxdepth is not None and maxdepth < 0: print padding[:-1] + ' `' + bold(blue('...')) return if last: print padding[:-1] + ' `' + bold( blue(self._keyfnc(self.group) + '/')) padding = padding[:-1] + ' ' else: print padding + '`' + bold(blue(self._keyfnc(self.group) + '/')) count = len(self) large = False if maxcount is not None and count > maxcount: count = maxcount + 1 large = True if self is None or not count: print padding, ' `' + boldblack('[empty]') else: for key, val in self.iteritems(): count -= 1 if count == 0 and large: #print padding + ' |-'+(cyan('(...)')) print padding + ' ' + '`...' break self._printNode(key, val, padding=padding + ' |', last=not count, maxdepth=maxdepth - 1, maxcount=maxcount)
def user_input(self): intrare = input(bold("On wich position (0-8) :")) if len(intrare) != 1: return self.user_input() if ord('0') <= ord(intrare) <= ord('8'): return int(intrare) else: return self.user_input()
def printTree(self, padding= '', last=False,maxdepth=3,maxcount=50): """Print tree contained in file. Parameters ---------- padding : string Arguements passed in command line. last : boolean Last node in sequence maxdepth : number Limit dept maxcount : number Limit count """ if maxdepth is not None and maxdepth<0: print padding[:-1] + ' `'+bold(blue('...')) return if last: print padding[:-1] + ' `' + bold(blue(self._keyfnc(self.group) + '/' )) padding = padding[:-1]+' ' else: print padding + '`' + bold(blue(self._keyfnc(self.group) + '/') ) count = len(self) large = False if maxcount is not None and count>maxcount: count=maxcount+1 large = True if self is None or not count: print padding, ' `'+boldblack('[empty]') else: for key, val in self.iteritems(): count -= 1 if count==0 and large: #print padding + ' |-'+(cyan('(...)')) print padding + ' '+'`...' break self._printNode(key,val,padding=padding+' |',last=not count,maxdepth=maxdepth-1,maxcount=maxcount)
def diff_all_table_data(self): failures = 0 self.create_aggregate_functions() print(bold(red('Starting table analysis.'))) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) tables = sorted( self.firstinspector.get_table_names(schema="public")) for table in tables: status_update = StatusUpdate( f"Analysing table {table}. " f"[{tables.index(table) + 1}/{len(tables)}]") result, message = self.diff_table_data(table) status_update.complete(result, f"{table} - {message}") if result is False: failures += 1 print(bold(green('Table analysis complete.'))) if failures > 0: return 1 return 0
def waiting_for_connection(): print("\n\n") print( text.Text(" VIA Protocol", color='#288D28', shadow=False, skew=1, fsize=10)) print(bold(white("SENDER'S PLATFORM \n"))) print( bold( white( "Check logs in Sender-log.txt when the communication has ended\n" ))) print(bold(white("Type ':exit' to end the communication\n"))) print(bold(white("Waiting to connect"))) global connection animation = "|/-\\" idx = 0 while not connection: print(animation[idx % len(animation)], end="\r") idx += 1 time.sleep(0.1)
def run_as_checker(args): """Check for outstanding TODOs""" outstanding = [] with open(args.file, 'r') as todofile: for line in todofile.readlines(): if dt.today() > dt.strptime(line[:10], '%Y-%m-%d'): outstanding.append(line) if outstanding: print(color.bold(color.red( 'Warning! You should have already done this!:\n' '--------------------------------------------'))) for todo in outstanding: print(todo[:-1])
def diff_all_sequences(self, thread_number): # run just once if thread_number > 0: return 0 print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) failures = 0 for sequence in sequences: with Halo(text=f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]", spinner='dots') as spinner: result, message = self.diff_sequence(sequence) if result is True: spinner.succeed(f"{sequence} - {message}") elif result is None: spinner.warn(f"{sequence} - {message}") else: failures += 1 spinner.fail(f"{sequence} - {message}") print(bold(green('Sequence analysis complete.'))) if failures > 0: return 1 return 0
def error(msg, stacktrace=None): """Print an error message and exit. Params: ------- msg: str Error message. stacktrace: str Stacktrace. """ if stacktrace: print(stacktrace) print(bold(red(msg))) sys.exit(1)
def run_as_checker(args): """Check for outstanding TODOs""" outstanding = [] with open(args.file, 'r') as todofile: for line in todofile.readlines(): if dt.today() > dt.strptime(line[:10], '%Y-%m-%d'): outstanding.append(line) if outstanding: print( color.bold( color.red('Warning! You should have already done this!:\n' '--------------------------------------------'))) for todo in outstanding: print(todo[:-1])
def end_connection(): sock.close() print(bold(white("\n\nConnection closed!!!"))) print( text.Text(" END", color='#288D28', shadow=False, skew=1, fsize=10)) f.write( "\n\n ------------------------------------------------------------------------------\n" ) f.write("\n\nConnection Closed\n") f.write("Total Messages : " + str(counter) + "\n") f.write("Date and Iime : " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + "\n\n") f.close()
def exchange_public_keys(): global bobPublicKey global sock global connection data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes connection = True if (inception): print(bold(white("\nConnection Established!!\n\n"))) sock.settimeout(2) bobPublicKey = int(data.decode()[0:]) global alicePublicKey global ip alicePublicKey = (base**alicePrivateKey) % modulus sock.sendto(str(alicePublicKey).encode(), addr) ip = addr
def send_message(): #keep sending messages until user sends :exit while (True): global Message global firstMessage global NextKey global currentKey global ip global sameMessage global sameKeys global counter #check if same key has to be used for encryption in case of retransmission if (not sameKeys): if (firstMessage): currentKey = sharedKey NextKey = randint(1, 127) firstMessage = False else: currentKey = NextKey NextKey = randint(1, 127) else: sameKeys = False if (not sameMessage): Message = input("Enter the message here : ") else: sameMessage = False # add shared key and next key to the message as a single character payload = Message + chr(sharedKey) + chr(NextKey) #generate hash hash = sha256(payload.encode()).hexdigest() #encrypt the message cipher = encrypt(payload + hash, currentKey) sock.sendto((str(counter) + str(cipher)).encode(), ip) f.write(str(counter) + "." + "\n") f.write("Message sent : " + Message + "\n") f.write("Next Key : " + str(NextKey) + "\n") f.write("Message with payload : " + payload + "\n") f.write("Hash of the message with payload : " + hash + "\n") f.write("Encrption : " + cipher + "\n") #check if ack recieved or not try: data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes except Exception: print( bold( red("Connection timed out. ACK not received. Sending the message again\n" ))) f.write( "Connection timed out. ACK not received. Sending the message again" + "\n") sameMessage = True sameKeys = True continue #check if ack/nack received valid = int(data.decode()[0:]) if (valid == 0): print( bold( red("NACK recieved. Generating and exchanging keys again. Sending the message again \n" ))) f.write( "NACK recieved. Generating and exchanging keys again. Sending the message again \n" ) counter = 0 firstMessage = True sameMessage = True diffie_hellman() break else: f.write("ACK recieved\n") counter = counter + 1 f.write("\n") #end connection if :exit sent if (Message == ":exit"): end_connection() break
import subprocess from fabulous.color import bold, blue, green import time import requests import random import mhutils hub_address = mhutils.get_address("keys/hub.pub") co = 100 while True: co += int((random.random() - 0.5) * 10) print(bold("Current CO level:"), green(str(co))) transaction_result = subprocess.check_output([ "python3", "metahash.py", "send-tx", "--net=test", "--pubkey=keys/co.pub", "--privkey=keys/co.priv", "--value=1", "--to={}".format(hub_address), '--data=' + str(co) ]).decode("utf-8") print(transaction_result) time.sleep(5)
downhill=False, stairs=False, seed_value=args.seed, on_rack=False, gait='trot') steps = 0 t_r = 0 if (args.RandomTest): env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) state = env.reset() print(bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'), red(env.incline_deg), green('\nWedge Orientation:'), red(math.degrees(args.WedgeOrientation)), green('\nCoeff. of friction:'), red(env.friction), green('\nMotor saturation torque:'), red(env.clips)) for i_step in range(args.EpisodeLength): print('Roll:', math.degrees(env.support_plane_estimated_roll), 'Pitch:', math.degrees(env.support_plane_estimated_pitch)) action = policy.dot(state) # action = [1.0,1.0,1.0,1.0, # 0.0,0.0,0.0,0.0, # -1.0,-1.0,-1.0,-1.0, # -1.0,-1.0,-1.0,-1.0, # 0.0,0.0,0.0,0.0 ] # action = [0.5,0.5,0.5,0.5,
asctime=col.fg256(pal['44m'], '{r.asctime}'), module=col.fg256(pal['44m'], '{r.module}'), levelname=col.fg256(pal['44m'], '{r.levelname}'), msg=col.fg256(pal['44m'], '{r.msg}'), ), 'INFO': '{asctime} {module} {levelname} {msg}'.format( asctime=col.fg256(pal['43m'], '{r.asctime}'), module=col.fg256(pal['43m'], '{r.module}'), levelname=col.fg256(pal['43m'], '{r.levelname}'), msg=col.fg256(pal['43m'], '{r.msg}'), ), 'WARNING': '{asctime} {module} {levelname} {msg}'.format( asctime=col.fg256(pal['41m'], '{r.asctime}'), module=col.fg256(pal['41m'], '{r.module}'), levelname=col.fg256(pal['41m'], '{r.levelname}'), msg=col.fg256(pal['41m'], '{r.msg}'), ), 'ERROR': '{asctime} {module} {levelname} {msg}'.format( asctime=col.fg256(pal['45m'], '{r.asctime}'), module=col.fg256(pal['45m'], '{r.module}'), levelname=col.fg256(pal['45m'], '{r.levelname}'), msg=col.fg256(pal['45m'], '{r.msg}'), ), 'CRITICAL': '{asctime} {module} {levelname} {msg}'.format( asctime=col.fg256(pal['45m'], '{r.asctime}'), module=col.fg256(pal['45m'], '{r.module}'), levelname=col.bold(col.fg256(pal['45m'], '{r.levelname}')), msg=col.bold(col.fg256(pal['45m'], '{r.msg}')), ), }
def print_results(self, result_list, engine="default"): print('{}:'.format(bold(engine))) for title, company, url in result_list: print('{}'.format(bold(title))) print('{}'.format(company)) print('{}\n'.format(url))
def log(obj): now = datetime.now().strftime("%m/%d/%Y %H:%M:%S") message = f">{now} -- {obj}" print(bold(green(message)))
def __init__(self, name): self.name = name self.printable_name = bold(magenta(self.name)) self.score = 0
import subprocess from fabulous.color import bold, blue, green import time import random import mhutils hub_address = mhutils.get_address("keys/hub.pub") temp = 20 while True: temp += (random.random() - 0.5) print(bold("Current temperature:"), green("{:.1f}".format(temp))) transaction_result = subprocess.check_output([ "python3", "metahash.py", "send-tx", "--net=test", "--pubkey=keys/temp.pub", "--privkey=keys/temp.priv", "--value=1", "--to={}".format(hub_address), '--data=' + "{:.1f}".format(temp) ]).decode("utf-8") print(transaction_result) time.sleep(5)
module=col.fg256(pal['base03.5'], '{r.module}'), levelname=col.fg256(pal['base0C'], '{r.levelname}'), msg=col.fg256(pal['base02'], '{r.msg}'), ), 'INFO': '{asctime} {module} {levelname} {msg}'.format( asctime=col.fg256(pal['base03'], '{r.asctime}'), module=col.fg256(pal['base03.5'], '{r.module}'), levelname=col.fg256(pal['base0B'], '{r.levelname}'), # levelname=col.fg256(pal['base06'], '{r.levelname}'), msg=col.fg256(pal['base02'], '{r.msg}'), ), 'WARNING': '{asctime} {module} {levelname} {msg}'.format( asctime=col.fg256(pal['base03'], '{r.asctime}'), module=col.fg256(pal['base03.5'], '{r.module}'), levelname=col.fg256(pal['base0A'], '{r.levelname}'), msg=col.fg256(pal['base02'], '{r.msg}'), ), 'ERROR': '{asctime} {module} {levelname} {msg}'.format( asctime=col.fg256(pal['base03'], '{r.asctime}'), module=col.fg256(pal['base03.5'], '{r.module}'), levelname=col.fg256(pal['base08'], '{r.levelname}'), msg=col.fg256(pal['base08'], '{r.msg}'), ), 'CRITICAL': '{asctime} {module} {levelname} {msg}'.format( asctime=col.fg256(pal['base03'], '{r.asctime}'), module=col.fg256(pal['base03.5'], '{r.module}'), levelname=col.bold(col.fg256(pal['base08'], '{r.levelname}')), msg=col.bold(col.fg256(pal['base08'], '{r.msg}')), ), }
import subprocess from fabulous.color import bold, blue, green import time import random import mhutils hub_address = mhutils.get_address("keys/hub.pub") temp_address = mhutils.get_address("keys/temp.pub") heater_is_on = False while True: last_temp = mhutils.get_last_data_from_address( mhutils.get_history(hub_address), temp_address) print(bold("Current temperature:"), green(bold(last_temp))) if heater_is_on != (float(last_temp) < 20): heater_is_on = float(last_temp) < 20 print(heater_is_on) transaction_result = subprocess.check_output([ "python3", "metahash.py", "send-tx", "--net=test", "--pubkey=keys/heater.pub", "--privkey=keys/heater.priv", "--value=1", "--to={}".format(hub_address), '--data=' + str(heater_is_on) ]).decode("utf-8") print(transaction_result) time.sleep(5)
from terminaltables import SingleTable from fabulous.color import bold, bg256, fg256 print(bold('ana are text bold'), 'dar si text normal') print(bg256('#DDD', 'dar si text pe fundal gri')) data = [['X', 'O', 'X'], [' ', 'O', ' '], ['X', ' ', ' ']] table = SingleTable(data) table.inner_row_border = True print(table.table)
def print_color(r, g, b): pad = " " pad2 = " " print bold(bg256("#%.2x%.2x%.2x" % (r, g, b), "%s" % pad + " #%.2x%.2x%.2x " % (r, g, b) + "%s" % pad2))
#!/usr/bin/env python """Colour theme for terminals which support only 8-bit colors. """ from fabulous import color as col messagefmt = { None: '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.cyan('{r.levelname}'), msg=col.bold(col.yellow('{r.msg}')), ), 'INFO': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.green('{r.levelname}'), msg=col.bold(col.yellow('{r.msg}')), ), 'WARNING': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.bold(col.magenta('{r.levelname}')), msg=col.bold(col.yellow('{r.msg}')), ), 'ERROR': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'),
if (args.RandomTest): env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) env.SetFootFriction(args.FrictionCoeff) # env.SetLinkMass(0,args.FrontMass) # env.SetLinkMass(11,args.BackMass) env.clips = args.MotorStrength env.pertub_steps = 300 env.y_f = args.PerturbForce state = env.reset() print( bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'), red(env.incline_deg), green('\nWedge Orientation:'), red(math.degrees(env.incline_ori)), green('\nCoeff. of friction:'), red(env.friction), # green('\nMass of the front half of the body:'),red(env.FrontMass), # green('\nMass of the rear half of the body:'),red(env.BackMass), green('\nMotor saturation torque:'), red(env.clips)) # Simulation starts simstep = 1000 plot_data = [] t_r = 0
class CliFormatter(string.Formatter): """ Extends string.Formatter to provide some bells and whistles: Tabular Data - `{foo:table}`: tabular_data = [('foo-header', 'bar-header'), ('row1, col1', 'row1, col2)'] # and so on... formatter.format('Here is a table\n{totally_tabular:table}', totally_tabular=tabular_data) ANSI Style Markup - `{foo:bold}`: formatter.format('{good:256_bright_green}, {bad:256_bright_red}', good="Awesome!", bad="Oh no!") Format raw text without an explicit value: formatter.format('{Awesome!:256_bright_green}, {Oh no!:256_bright_red}') # normally would raise a KeyError Auto de-dent - dedent=True (default): multiline_string = ''' Normally this would be printed with the leading/trailing \\n and spaces. You could call textwrap.dedent() on the resulting string but the formatter handles it for you. ''' formatter.format('No indention:\n{}', multiline_string) # dedent=true by default formatter.format('Indention:\n{}', multiline_string, dedent=False) """ STYLES = { 'bold': lambda text: color.bold(text), 'italic': lambda text: color.italic(text), 'strike': lambda text: color.strike(text), 'underline': lambda text: color.underline(text), '256_bright_green': lambda text: color.bold(color.fg256('#00FF00', text)), '256_green': lambda text: color.bold(color.fg256('#00FF00', text)), '256_light_green': lambda text: color.fg256('#99ff00', text), '256_bright_yellow': lambda text: color.bold(color.fg256('#ffdd00', text)), '256_yellow': lambda text: color.fg256('#ffdd00', text), '256_light_yellow': lambda text: color.fg256('#ffff00', text), '256_bright_red': lambda text: color.bold(color.fg256('#ff0000', text)), '256_red': lambda text: color.bold(color.fg256('#ff0000', text)), '256_light_red': lambda text: color.fg256('#ff5500', text), } def __init__(self): super(CliFormatter, self).__init__() self.indent_level = 0 self.dedent = True def format(self, *args, **kwargs): """ You can use 'dedent' to have the formatter de-indent the final string for you which is nice when you are using heredoc style strings that preserve white space in a multiline string. :param args: :param kwargs: :return: """ if 'dedent' in kwargs: self.dedent = kwargs['dedent'] del kwargs['dedent'] formatted = super(CliFormatter, self).format(*args, **kwargs) if self.dedent: formatted = textwrap.dedent(formatted).strip('\n') self.dedent = True self.indent_level = 0 return formatted def vformat(self, format_string, args, kwargs): """ Need to keep track of the indent level incase we generate new rows of text, e.g. a Table, so the indention level of the generated row matches :param format_string: :param args: :param kwargs: :return: """ if isinstance(format_string, str): self.indent_level = len(format_string) - len(format_string.lstrip()) - 1 return super(CliFormatter, self).vformat(format_string, args, kwargs) def get_value(self, key, args, kwargs): """ Normally a key without a matching value would raise an error, but I want to be able to stylize plain text without having to make a variable and stick it in a map, e.g. formatter.format('{This is a string:bold}') instead of formatter.format('{placehold:bold}', {'placeholder': 'This is a string'}) :param key: :param args: :param kwargs: :return: """ try: return super(CliFormatter, self).get_value(key, args, kwargs) except (IndexError, KeyError) as e: return key def format_field(self, value, format_spec): if format_spec == 'table' or format_spec == 'table_no_header': header = format_spec == 'table' return tabulate(value, first_row_header=header, indent_level=self.indent_level) elif format_spec in CliFormatter.STYLES: stylized = CliFormatter.STYLES[format_spec](value) return str(stylized) else: return super(CliFormatter, self).format_field(value, format_spec)
def print_color(r, g, b): pad = ' ' pad2 = ' ' print bold( bg256('#%.2x%.2x%.2x' % (r, g, b), '%s' % pad + ' #%.2x%.2x%.2x ' % (r, g, b) + '%s' % pad2))
def bold(self): return ansi(c.bold(self.txt))