class Input(object): prompt = '?> ' def __init__(self, config): self.config = config self.term = Terminal() self.commands = {} for name, member in inspect.getmembers(self): if inspect.ismethod(member) and name.startswith('do_'): self.commands[name[3:]] = member.__doc__ # A Command self.say_hello() self.say_prompt() def _validate(self, cmd): if cmd in self.commands: getattr(self, 'do_{}'.format(cmd))() else: print 'ERROR' def say_hello(self): if self.intro: print self.term.bold(self.intro) print '-'*len(self.intro) if self.commands: for name, help in self.commands.items(): print self.term.bold(name), ' ', help def say_prompt(self): input = raw_input(self.prompt) self._validate(input)
class FanDriver(Thread): def __init__(self, headers): Thread.__init__(self) self.headers = headers self.config = json.load(open('/home/pi/bitrepublic/Config.json')) self.address = self.config["requests"]["fan"]["Address"] self.p = GPIO.PWM(13, 100) self.p.start(0) self.t = Terminal() print(self.t.bold('Hi there! : I\'m the Fan driver')) def run(self): while True: print(self.t.bold('Fandriver : is there any new bitsoil ?')) r = requests.get(self.address, headers=self.headers) #send the get request. if r.status_code == 200: #checks if the server respond jdata = r.json() if jdata["data"] != False: #checks if there is data in the output of the server. print( self.t.bold( 'Fandriver : Yes ! so let the wind blow your mind') ) self.p.ChangeDutyCycle(100) time.sleep(random.randint(10, 20)) #p.stop() #GPIO.cleanup() self.p.ChangeDutyCycle(0) t = random.randint(2, 6) print(self.t.bold('Fandriver : I need a small nap.')) time.sleep(t)
class Input(object): prompt = '?> ' def __init__(self, config): self.config = config self.term = Terminal() self.commands = {} for name, member in inspect.getmembers(self): if inspect.ismethod(member) and name.startswith('do_'): self.commands[name[3:]] = member.__doc__ # A Command self.say_hello() self.say_prompt() def _validate(self, cmd): if cmd in self.commands: getattr(self, 'do_{}'.format(cmd))() else: print 'ERROR' def say_hello(self): if self.intro: print self.term.bold(self.intro) print '-' * len(self.intro) if self.commands: for name, help in self.commands.items(): print self.term.bold(name), ' ', help def say_prompt(self): input = raw_input(self.prompt) self._validate(input)
class GPUStat: def __init__(self, server_list): self.server_list = server_list self.gpu_hosts = [] for server in server_list: gpu = GPUHost(server['username'], server['ip']) self.gpu_hosts.append(gpu) print('find %d gpu hosts' % len(self.gpu_hosts)) self.t = Terminal() atexit.register(self.exit) # disconnect def exit(self): for gpu in self.gpu_hosts: gpu.disconnect() print("exit success") def get_remote_gpu_stats(self): gpu_stats = { gpu._address: gpu.get_gpu_info() for gpu in self.gpu_hosts } return gpu_stats def print_stats(self): gpu_stats = self.get_remote_gpu_stats() # with self.t.fullscreen(): now = time.asctime(time.localtime(time.time())) print("%s | found %d gpu hosts" % (now, len(self.gpu_hosts))) for ip in gpu_stats: self.print_one_gpu(ip, gpu_stats[ip]) def print_one_gpu(self, ip, gpu_stat): print(('\n{t.bold}{t.black}{t.on_white}%s{t.normal}' % (ip)).format(t=self.t)) print( self.t.bold( '-----------------------------------------------------------------------------' )) for gpu in gpu_stat: print(( '{t.bold}{t.magenta}%d {t.white}|{t.blue} %s {t.white}| {t.bold}{t.red}%s{t.white}/{t.green}%s{t.white} | {t.white} fan: %s (%s) | process: %d{t.normal}' % (gpu['idx'], gpu['model'], gpu['mem_used'], gpu['mem_total'], gpu['fan_speed'], gpu['temp'], len(gpu['pids']))).format( t=self.t)) for id, pid in enumerate(gpu['pids']): print(( "{t.bold}{t.cyan}[%d]{t.yellow}%s\t{t.white}%s\t{t.white}%s\t{t.white}%s{t.normal}" % (id, pid['user'], pid['pid'], pid['used_momery'], pid['uptime'])).format(t=self.t)) print( self.t.bold( '-----------------------------------------------------------------------------' ))
def print_exit_msg(): term = Terminal() print "\n\nEnd of Line.\n\n" print ( " " + term.bold(term.green("<")) + "bn" + term.bold(term.green("/>")) ) print " Benito-Nemitz Inc."
def main(): term = Terminal() args = get_args() dir = '.' if args.path: dir = args.path print dir pattern = re.compile(args.regex) fname_pattern = re.compile(r".+") if args.file_name_pattern: fname_pattern = re.compile(args.file_name_pattern) lA, lB = 0, 0 if args.l_before: lB = args.l_before if args.l_after: lA = args.l_after blacklist = [] if args.exclude_paths: blacklist = args.exclude_paths.split(',') for root, dirs, files in os.walk(dir): if root in blacklist: continue for fname in files: if fname_pattern.match(fname): try: file_path = os.path.join(root, fname) with open(file_path, 'r') as source_file: contents = source_file.read() if pattern.search(contents): print term.bold("\n--- " + file_path + ':') content_lines = contents.split('\n') for line_no in range(len(content_lines)): m_obj = pattern.search( content_lines[line_no] + '\n') if m_obj: start = max(line_no - lB, 0) end = min(line_no + lA + 1, len(content_lines) - 1) line_nos = range(start, end) snippet = content_lines[start:end] # snippet_with_line_nos = [str(x[0]) + ' ' + x[1] for x in zip(line_nos, snippet)] csnippet = colorize( line_nos, line_no, snippet, m_obj, term ) pretty_print('\n'.join(csnippet)) except IOError as e: print e
def github_course(course: Dict[str, Any], g: Github, t: Terminal): repo_pattern = re.compile(course['repo_regex']) org = g.get_organization(course['organization']) print(org) repos = {} for repo in org.get_repos(): if not repo_pattern.fullmatch(repo.name): continue # add repo print(repo.name) repos[repo.name] = repo repo.issues = {} for issue in repo.get_issues(sort='created', direction='asc'): # state='closed' # add issue repo.issues[issue.number] = issue # sort by creation of first (open) issue repos_with_issue = [repo for repo in repos.values() if len(repo.issues) > 0] for repo in sorted(repos_with_issue, key=lambda k: list(k.issues.values())[0].created_at): print('\n{}: (forks: {}, last push: {})'.format(repo.name, repo.forks_count, repo.pushed_at)) for issue in repo.issues.values(): depth = 1 if issue.pull_request: pr = repo.get_pull(issue.number) else: pr = None issue_type = 'pr' if pr else 'issue' issue_template = '{issue_type} {number}: {title}' \ ' (created: {created_at}, labels: [{labels}], assignees: [{assignees}])' iprint(issue_template.format( issue_type=issue_type, number=t.bold(str(issue.number)), title=issue.title, created_at=issue.created_at, labels=', '.join([t.bold(label.name) for label in issue.labels]), assignees=', '.join([t.bold(assignee.login) for assignee in issue.assignees])), depth) depth = 2 iprint('{}'.format(issue.html_url), depth) if pr: iprint('state: {}, merge status: {}'.format(t.bold(pr.state), pr.mergeable_state), depth) iprint('+ {}, - {} ({} files changed)'.format(pr.additions, pr.deletions, pr.changed_files), depth)
def select_chromecast(cls): name = None chromecasts = pychromecast.get_chromecasts_as_dict().keys() if not chromecasts: return if len(chromecasts) > 1: term = Terminal() print(term.clear()) print(term.bold("Touchandgo\n")) print(term.red("Chromecasts Availables")) for i, cc_name in enumerate(chromecasts, 1): option = term.cyan("%s) " % i) option += cc_name print(option) input_text = "Select which chromecast you want to cast (1-%d): " % \ len(chromecasts) user_input = raw_input(input_text) try: opt = int(user_input) - 1 if opt > len(chromecasts) or opt < 1: opt = 0 except ValueError: opt = 0 name = chromecasts[opt] elif len(chromecasts) == 1: name = chromecasts[0] return name
def console(): t = Terminal() # clear screen print(t.clear, end="") # retrieve vended display object try: calculon.disp = Pyro4.Proxy(ENV['uri']) except: print(t.bold("Failed to connect to display")) calculon.disp = None repl.disp = calculon.disp # connect to voltron calculon.V = VoltronProxy() calculon.V.disp = calculon.disp calculon.V.update_disp() # run repl code.InteractiveConsole.runsource = repl.CalculonInterpreter().runsource code.interact(local=locals()) # clean up calculon.V._disconnect() if calculon.disp: calculon.disp._pyroRelease()
def show_progress(siteId, groupId, curr, total): '''Show the progress for sending the digest :param str siteId: The identifier for the site that contains the group. :param str groupId: The identifier for the group. :param int curr: The current index of the group. :param int total: The total number of groups. :func:`show_progress` displays the *verbose* feedback, including the name of the site and group. A progress bar is also displayed if the terminal supports it.''' t = Terminal() # Write the site and group if curr > 0 and t.does_styling: # Clear the line above (the progress bar) sys.stdout.write(t.move_up + t.move_x(0) + t.clear_eol) sys.stdout.flush() m = 'Sending digest to {0} on {1}\n' sys.stdout.write(t.white(m.format(groupId, siteId))) # Display progress if t.does_styling: # Length of the bar = (width of term - the two brackets) * progress p = int(((t.width - 2) * (curr / total))) bar = '=' * (p + 1) # +1 because Python is 0-indexed # Space at end = terminal width - bar width - brackets - 1 # (0-indexed) space = ' ' * (t.width - p - 3) sys.stdout.write(t.bold('[' + bar + space + ']\n')) sys.stdout.flush()
def _print_stream_item(self, item, pattern=None): print("") term = Terminal() time_label = "%s at %s" % (term.yellow(item.time.strftime("%a, %d %b %Y")), term.yellow(item.time.strftime("%H:%M"))) print("%s on %s:" % (term.cyan(item.source), time_label)) title = item.title if title is not None: if pattern is not None: title = pattern.sub(term.bold_black_on_bright_yellow("\\g<0>") + term.bold, title) print(" %s" % term.bold(title)) excerpter = TextExcerpter() excerpt, clipped_left, clipped_right = excerpter.get_excerpt(item.text, 220, pattern) # Hashtag or mention excerpt = re.sub("(?<!\w)([#@])(\w+)", term.green("\\g<1>") + term.bright_green("\\g<2>"), excerpt) # URL in one of the forms commonly encountered on the web excerpt = re.sub("(\w+://)?[\w.-]+\.[a-zA-Z]{2,4}(?(1)|/)[\w#?&=%/:.-]*", term.bright_magenta_underline("\\g<0>"), excerpt) if pattern is not None: # TODO: This can break previously applied highlighting (e.g. URLs) excerpt = pattern.sub(term.black_on_bright_yellow("\\g<0>"), excerpt) print(" %s%s%s" % ("... " if clipped_left else "", excerpt, " ..." if clipped_right else "")) print(" %s" % term.bright_blue_underline(item.link))
class TerminalView: """ Terminal view to basic CLI information. """ def __init__(self): self.term = Terminal() def print_error_and_exit(self, message): """ Print an error in red and exits the program. """ sys.exit(self.term.bold_red('[ERROR] ' + message)) def print_info(self, message): """ Print an informational text. """ print(message) def text_in_color(self, message, color_code): """ Print with a beautiful color. See codes at the top of this file. """ return self.term.color(color_code) + message + self.term.normal def format_question(self, message): """ Return an info-formatted string. """ return self.term.bold(message)
async def task_term_info(body): task = await fetch_task(body["status"]["taskId"]) name = task["metadata"]["name"] description = task["metadata"]["description"] task_id = body["status"]["taskId"] t = Terminal() return "{} {} {}".format(t.bold(task_id), name, t.dim(description))
def main(): term = Terminal() args = get_args() dir = '.' if args.path: dir = args.path print dir pattern = re.compile(args.regex) fname_pattern = re.compile(r".+") if args.file_name_pattern: fname_pattern = re.compile(args.file_name_pattern) lA, lB = 0, 0 if args.l_before: lB = args.l_before if args.l_after: lA = args.l_after blacklist = [] if args.exclude_paths: blacklist = args.exclude_paths.split(',') for root, dirs, files in os.walk(dir): if root in blacklist: continue for fname in files: if fname_pattern.match(fname): try: file_path = os.path.join(root, fname) with open(file_path, 'r') as source_file: contents = source_file.read() if pattern.search(contents): print term.bold("\n--- " + file_path + ':') content_lines = contents.split('\n') for line_no in range(len(content_lines)): m_obj = pattern.search(content_lines[line_no] + '\n') if m_obj: start = max(line_no - lB, 0) end = min(line_no + lA + 1, len(content_lines) - 1) line_nos = range(start, end) snippet = content_lines[start:end] # snippet_with_line_nos = [str(x[0]) + ' ' + x[1] for x in zip(line_nos, snippet)] csnippet = colorize( line_nos, line_no, snippet, m_obj, term) pretty_print('\n'.join(csnippet)) except IOError as e: print e
def suggest(**kwargs): common = common_args(**kwargs) if check_syntax(tokens_to_source_code(common.tokens)): print("No need to fix: Already syntactically correct!") return least_agreements = [] forwards_predictions = [] backwards_predictions = [] sent_forwards = Sentences(common.file_vector, size=SENTENCE_LENGTH, backwards=False) sent_backwards = Sentences(common.file_vector, size=SENTENCE_LENGTH, backwards=True) # Predict every context. contexts = enumerate(zip(chop_prefix(common.tokens, PREFIX_LENGTH), sent_forwards, chop_prefix(sent_backwards))) # Find disagreements. for index, (token, (prefix, x1), (suffix, x2)) in contexts: prefix_pred = common.forwards_model.predict(prefix) suffix_pred = common.backwards_model.predict(suffix) # Get its harmonic mean mean = consensus(prefix_pred, suffix_pred) forwards_predictions.append(index_of_max(prefix_pred)) backwards_predictions.append(index_of_max(suffix_pred)) paired_rankings = rank(mean) min_token_id, min_prob = paired_rankings[0] least_agreements.append(Agreement(min_prob, index)) fixes = Fixes(common.tokens) # For the top disagreements, synthesize fixes. least_agreements.sort() for disagreement in least_agreements[:3]: pos = disagreement.index # Assume an addition. Let's try removing some tokens. fixes.try_remove(pos) # Assume a deletion. Let's try inserting some tokens. fixes.try_insert(pos, id_to_token(forwards_predictions[pos])) fixes.try_insert(pos, id_to_token(backwards_predictions[pos])) if not fixes: t = Terminal() print(t.red("I don't know how to fix it :C")) return -1 t = Terminal() for fix in fixes: header = t.bold("{filename}:{line}:{column}:".format( filename=common.filename, line=fix.line, column=1 + fix.column )) print(header, fix)
def show_events(city): events = [['Group Name', 'Venue Name','Address', 'URL']] + get_events(city) terminal = Terminal() print "Showing events from city:", terminal.bold(city) event_table = AsciiTable(events) print event_table.table
def main(): sys.stderr.write("\x1b[2J\x1b[H") term = Terminal() task = process_input() if not task: task = 'Important stuff' print term.bold(task) h = 1 i = 0 limit = 10**5 vals = np.random.random(limit) * 10 prompt = "Progress:" sep = '|' units = 'bits' padding = ' ' * max(3, int(term.width * 0.025)) rhs = len(str(limit)) * 2 + len(sep) + len(units) lhs = len(prompt) + 5 maxbarsize = max(0, int(term.width * .9) - rhs - lhs - len(padding)) def makeLine(idx = None): if not idx: idx = i n = ('%0.0f' % (float(idx)/limit * 100)).zfill(2) pct = '(%s%s)' % (n, '%') right = ('%d %s %d %s' % (idx, sep, limit, units)).rjust(rhs) bar = '=' * int(float(idx) / limit * maxbarsize) space = ' ' * (maxbarsize - len(bar)) mid = '%s[%s>%s]%s' % (' ', bar, space, padding) return ' '.join([prompt, pct, mid, right]) print makeLine() last = time.time() while i < limit: if time.time() - last > 0.3: time.sleep(.05) print term.move(h, 0) + makeLine() last = time.time() if i < len(vals): time.sleep(vals[i]/10**5) i += vals[i] else: i += np.random.randint(10) print term.move(h, 0) + makeLine(limit) print term.bold('Success!')
def format_fix(filename: Path, fix: Edit) -> None: """ Prints a fix for the given filename. """ suggestion = Suggestion.enclose(filename, fix) line = suggestion.line column = suggestion.column t = Terminal() # Use a format similar to Clang's. header = t.bold(f"{filename}:{line}:{column}:") print(header, suggestion)
def hg_diff(module, path, verbose, rev1, rev2): t = Terminal() try: msg = [] path_repo = path if not os.path.exists(path_repo): print >> sys.stderr, (t.red("Missing repositori:") + t.bold(path_repo)) return if not verbose: result = run('cd %s;hg diff --stat' % path_repo, hide='stdout') if result.stdout: msg.append(t.bold(module + "\n")) msg.append(result.stdout) print "\n".join(msg) return repo = hgapi.Repo(path_repo) if rev2 is None: rev2 = get_branch(path_repo) msg = [] for diff in repo.hg_diff(rev1, rev2): if diff: d = diff['diff'].split('\n') for line in d: if line and line[0] == '-': line = t.red + line + t.normal elif line and line[0] == '+': line = t.green + line + t.normal if line: msg.append(line) if msg == []: return msg.insert(0, t.bold('\n[' + module + "]\n")) print "\n".join(msg) except: msg.insert(0, t.bold('\n[' + module + "]\n")) msg.append(str(sys.exc_info()[1])) print >> sys.stderr, "\n".join(msg)
def run_report(self): """ Compile and print the task report. """ wdays = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] letters = 3 # No of letters to use for wday names. 1 - 3 istty = True indent = letters # The indent per week day # TODO "indent" is used and defined here an in construct_cmdline. Define once? if istty: # This is currently hard coded, but can be an input. term = Terminal() else: term = Terminal(stream="not tty") # When not run from a tty # Calcs how many task lines can fit onto the screen. taskspace = (term.height if term.is_a_tty else 40) - (5 + letters) # Compile the line showing each Monday's date. dateline = self.weekstart.strftime("%d %b %Y") if self.weeks > 1: # Add additional Mondays if required for week in range(1, self.weeks): # i.e. week 1 is the second week. # No of spaces to add on to existing dateline before # inserting next date weekindent = len(wdays) * week * indent - len(dateline) dateline = dateline + ' ' * weekindent + (self.weekstart + \ timedelta(days=7 * week)).strftime("%d %b %Y") # Position # Compile the day header sting (includes newlines) dayheader = '' for lineNo in range(letters): for day in wdays * self.weeks: # add the letter and spacing to indent for each day and makes mondays bold dayheader = dayheader + (term.bold(day[lineNo]) if (day == \ "MON" and not self.selector) else day[lineNo]) + ' ' \ * (indent - 1) dayheader = dayheader + '\n' # Compile the multiline string containing the tasklines taskstring = "" for task in self.tasks: # Step through list of task dictionary objects taskline, tdate = self.compile_taskline(task) if tdate.date() < date.today(): # Add newline if not end of list and colour red taskstring = taskstring + ('\n' if len(taskstring) != 0 else '') + term.red(taskline) elif tdate.date() == date.today(): taskstring = taskstring + '\n' + term.yellow(taskline) elif tdate.date() > date.today(): taskstring = taskstring + '\n' + taskline # Removes lines that will not fit onto screen terminal_lines = ''.join(taskstring.splitlines(True)[0:taskspace]) print dateline + '\n' + dayheader + terminal_lines
def print_matrix_with_fabulousness(matrix): t = Terminal() colors = [t.red, t.green, t.blue] if len(matrix) == 0: #print t.yellow('[]') return t.yellow('[') fmatrix = [['%.2f' % col for col in row] for row in matrix] ret_s = t.bold(' '.join([' '] + [str(c) for c in range(len(fmatrix[0]))]) + "\n") for n, row in enumerate(fmatrix): ret_s += colors[n % 3](' '.join([str(n)] + row) + "\n") return ret_s + '\n'
def run_report(self): """ Compile and print the task report. """ wdays = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] letters = 3 # No of letters to use for wday names. 1 - 3 istty = True indent = letters # The indent per week day # TODO "indent" is used and defined here an in construct_cmdline. Define once? if istty: # This is currently hard coded, but can be an input. term = Terminal() else: term = Terminal(stream="not tty") # When not run from a tty # Calcs how many task lines can fit onto the screen. taskspace = (term.height if term.is_a_tty else 40) - (5 + letters) # Compile the line showing each Monday's date. dateline = self.weekstart.strftime("%d %b %Y") if self.weeks > 1: # Add additional Mondays if required for week in range(1, self.weeks): # i.e. week 1 is the second week. # No of spaces to add on to existing dateline before # inserting next date weekindent = len(wdays) * week * indent - len(dateline) dateline = dateline + ' ' * weekindent + (self.weekstart + \ timedelta(days=7 * week)).strftime("%d %b %Y") # Position # Compile the day header sting (includes newlines) dayheader = '' for lineNo in range(letters): for day in wdays * self.weeks: # add the letter and spacing to indent for each day and makes mondays bold dayheader = dayheader + (term.bold(day[lineNo]) if (day == \ "MON" and not self.selector) else day[lineNo]) + ' ' \ * (indent - 1) dayheader = dayheader + '\n' # Compile the multiline string containing the tasklines taskstring = "" for task in self.tasks: # Step through list of task dictionary objects taskline, tdate = self.compile_taskline(task) if tdate.date() < date.today(): # Add newline if not end of list and colour red taskstring = taskstring + ('\n' if len(taskstring) != 0 else '' ) + term.red(taskline) elif tdate.date() == date.today(): taskstring = taskstring + '\n' + term.yellow(taskline) elif tdate.date() > date.today(): taskstring = taskstring + '\n' + taskline # Removes lines that will not fit onto screen terminal_lines = ''.join(taskstring.splitlines(True)[0:taskspace]) print dateline + '\n' + dayheader + terminal_lines
def handle_error(self, exc, trace): """ Error handler. Whatever happens in a plugin or component, if it looks like an exception, taste like an exception or somehow make me think it is an exception, I'll handle it. :param exc: the culprit :param trace: Hercule Poirot's logbook. :return: to hell """ from blessings import Terminal term = Terminal() print(term.bold(term.red('\U0001F4A3 {} in {}'.format(type(exc).__name__, self.wrapped)))) print(trace)
def run(self): term = Terminal() print("%s (%s)" % (term.bold("krill 0.3.0"), term.underline("https://github.com/p-e-w/krill"))) while True: try: self.update() if self.args.update_interval <= 0: break time.sleep(self.args.update_interval) except KeyboardInterrupt: # Do not print stacktrace if user exits with Ctrl+C sys.exit()
def github(t: Terminal): config = read_config(Path(expanduser('~')) / '.syslab-reviewer.yml') g = Github(config['github']['token']) user = g.get_user() print(user) print('You are logged in as: {} ({})'.format(user.name, t.bold(user.login))) courses = config['courses'] print('courses:\n', ', '.join([course['name'] for course in courses])) for course in courses: print('Course: {}'.format(course['name'])) github_course(course, g, t)
class Test: def __init__(self): self.t = Terminal() self.tests = 0 self.errors = 0 for i, test in enumerate(self.collect()): self.section = i + 1 if test.__doc__: print(self.t.bold(f'{self.section}. ' + test.__doc__)) test() print("") if self.errors == 0: print(f"Éxecuté {self.tests} tests avec succès\n\nOK") sys.exit(0) else: s = "s" if self.errors > 1 else "" print( f"Éxecuté {self.tests - self.errors} sur {self.tests} tests avec succès, {self.errors} erreur{s}\n\nFAIL" ) sys.exit(1) def collect(self): return [ getattr(self, method) for method in dir(self) if method.startswith('test_') ] def test(self, message, assertion, error_message=None): print(f" {self.section}.{self.tests + 1}. {message}...", end='', flush=True) if self._is_lambda(assertion): assertion = assertion() if assertion: print(self.t.green(" ok"), flush=True) else: self.errors += 1 print(self.t.red(" erreur"), flush=True) if error_message: print(self.t.red(" " + error_message)) self.tests += 1 @staticmethod def _is_lambda(v): LAMBDA = lambda: 0 return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
def hg_diff(module, path, rev1=None, rev2=None): t = Terminal() try: msg = [] path_repo = path if not os.path.exists(path_repo): print((t.red("Missing repositori: ") + t.bold(path_repo)), file=sys.stderr) return repo = hgapi.Repo(path_repo) if rev2 is None: rev2 = get_branch(path_repo) msg = [] for diff in repo.hg_diff(rev1, rev2): if diff: d = diff['diff'].split('\n') for line in d: if line and line[0] == '-': if module not in ['patches', 'features']: line = line.replace('--- a','--- a/'+path[2:] ) line = t.red + line + t.normal elif line and line[0] == '+': if module not in ['patches', 'features']: line = line.replace('+++ b','+++ b/'+path[2:] ) line = t.green + line + t.normal if line: msg.append(line) if msg == []: return msg.insert(0, t.bold('\n[' + module + "]\n")) print("\n".join(msg)) except: msg.insert(0, t.bold('\n[' + module + "]\n")) msg.append(str(sys.exc_info()[1])) print("\n".join(msg), file=sys.stderr)
def run(self): term = Terminal() print("%s (%s)" % (term.bold("krill++ 0.4.1"), term.underline("https://github.com/kyokley/krill"))) try: self.update() self.flush_queue(interval=0) if self.args.update_interval > 0: while True: time.sleep(self.args.update_interval) self.update() self.flush_queue(interval=self.text_speed) except KeyboardInterrupt: # Do not print stacktrace if user exits with Ctrl+C sys.exit()
def hg_revision(module, path, verbose=False): t = Terminal() path_repo = path if not os.path.exists(path_repo): print >> sys.stderr, (t.red("Missing repositori:") + t.bold(path_repo)) return False repo = hgapi.Repo(path_repo) branches = repo.get_branches() revision = False for branch in branches: if branch['name'] == repo.hg_branch(): revision = branch['version'].split(':')[1] return revision
class Test(metaclass=OrderedMeta): def __init__(self): self.t = Terminal() self.tests = 1 self.errors = 0 def run(self): for category, tests in self.collect().items(): for name, test in tests: if test.__doc__: print(name, self.t.bold(test.__doc__)) test() print("") if self.errors == 0: print(f"Successfully executed {self.tests} tests\n\nOK") sys.exit(0) else: s = "s" if self.errors > 1 else "" print( f"Successfully executed {self.tests - self.errors} of {self.tests} tests, {self.errors} error{s}\n\nFAIL" ) sys.exit(1) def collect(self): tests = defaultdict(list) for method in self._orderedKeys: if not method.startswith('test_'): continue func = getattr(self, method) category = func._category if hasattr(func, '_category') else 'Default' tests[func._category].append((method, func)) return tests def test(self, assertion, message=None, error_message=None): if message: print(f"{self.tests}. {message}...", end='', flush=True) else: print(f"{self.tests}. ", end='', flush=True) if assertion: print(self.t.green(" pass"), flush=True) else: self.errors += 1 print(self.t.red(" fail"), flush=True) if error_message: print(self.t.red(" " + error_message)) self.tests += 1
class TerminalView(object): """ Terminal view to basic CLI information. """ def __init__(self): self.term = Terminal() def print_error_and_exit(self, message): """ Print an error in red and exits the program. """ sys.exit(self.term.bold_red('[ERROR] ' + message)) def print_info(self, message): """ Print an informational text. """ #print(self.term.bold('[INFO] ') + message) print(message) def format_question(self, message): """ Return an info-formatted string. """ return self.term.bold(message)
def ui(): log = logging.getLogger('yadageui') maxheight = 30 banner = '''\ __ __ _____ ____/ /__ ____ ____ / // / _ `/ _ / _ `/ _ `/ -_) \_, /\_,_/\_,_/\_,_/\_, /\__/ /___/ /___/ ''' from blessings import Terminal rootlogger = logging.getLogger() handlers = [x for x in rootlogger.handlers] for x in handlers: rootlogger.removeHandler(x) rootlogger = logging.getLogger() rootlogger.addHandler(logging.FileHandler('bkg.log')) term = Terminal() with term.hidden_cursor(): for i in range(maxheight): print('') relmove(term, -maxheight) with term.location(): print(term.bold(banner)) while True: event = yield if not event: break with term.location(): try: handleevent(term, event) except: print('... UI exception ...') traceback.print_exc(file=sys.stdout) print('') relmove(term, maxheight) print('Workflow done. Good Bye.') for x in handlers: rootlogger.addHandler(x)
def main(): all_robots = { "eduro": "/home/robot/git/osgar/logs/", "k2": "/home/robot/git/osgar/logs/", "k3": "/home/robot/git/osgar/logs/", "mobos": "~/logs/", "maria": "~/logs/", } import argparse parser = argparse.ArgumentParser(description='rsync logs from robots') parser.add_argument('robots', nargs='*', choices=list(all_robots.keys()) + [[]], default=[]) args = parser.parse_args() if args.robots == []: robots = all_robots else: robots = {k: all_robots[k] for k in args.robots} home = str(Path.home()) t = Terminal() try: while True: for robot, logs in robots.items(): print(t.bold(f"Syncing {robot}:")) print(t.dim, end="", flush=True) a = subprocess.call([ "rsync", "-v", "--append", "--progress", "--recursive", f"{robot}:{logs}", f"{home}/logs/{robot}" ]) print(t.normal, end="", flush=True) if a == 0: print(t.green("OK")) else: print(t.red("Failed")) print() except KeyboardInterrupt: print(t.normal, flush=True)
class BitsoilGenerator(Thread): def __init__(self, headers): Thread.__init__(self) self.headers = headers self.config = json.load(open('/home/pi/bitrepublic/Config.json')) self.address = self.config["requests"]["genBitSoil"]["Address"] #self.p = GPIO.PWM(13, 100) #self.p.start(0) self.t = Terminal() self.oldState = False print(self.t.bold('Hi there! : I\'m the Bitsoil Generator')) QueueGen(headers) def run(self): while True: input_state = GPIO.input(17) if (self.oldState == False and input_state): print("ACTION") q.put("genbitsoil") self.oldState = input_state time.sleep(0.33)
def show_progress(profileId, curr, total): '''Show the progress for sending the profile :param str profileId: The identifier for the profile. :param int curr: The current index of the person. :param int total: The total number of people. :func:`show_progress` displays the *verbose* feedback. A progress bar is also displayed if the terminal supports it.''' t = Terminal() # Write the site and group m = 'Sending status ({0})...\n' sys.stdout.write(t.white(m.format(profileId))) # Display the progress bar if t.does_styling: # Length of the bar = (width of term - the two brackets) * progress p = int(((t.width - 2) * (curr / total))) bar = '=' * (p + 1) # +1 because Python is 0-indexed # Space at end = terminal width - bar width - brackets - 1 # (0-indexed) space = ' ' * (t.width - p - 3) sys.stdout.write(t.bold('[' + bar + space + ']\n')) sys.stdout.flush()
class Test: def __init__(self): self.t = Terminal() self.tests = 0 self.errors = 0 for i, test in enumerate(self.collect()): if test.__doc__: print(self.t.bold(test.__doc__)) test() print("") if self.errors == 0: print(f"Éxecuté {self.tests} tests avec succès\n\nOK") sys.exit(0) else: s = "s" if self.errors > 1 else "" print( f"Éxecuté {self.tests - self.errors} sur {self.tests} tests avec succès, {self.errors} erreur{s}\n\nFAIL" ) sys.exit(1) def collect(self): return [ getattr(self, method) for method in dir(self) if method.startswith('test_') ] def test(self, message, assertion, error_message=None): print(f"{self.tests}. {message}...", end='', flush=True) if assertion: print(self.t.green(" ok"), flush=True) else: self.errors += 1 print(self.t.red(" erreur"), flush=True) if error_message: print(self.t.red(" " + error_message)) self.tests += 1
def executeCmds(stat, **kwargs): # TODO: Documentation for executeCmds() t = Terminal() exeCmd = kwargs['cmd'] kwargs.update(stat) callback = kwargs["callback"] msg = "\n[Begin %s] " % exeCmd # exeCmd header = t.bold(t.yellow(msg))+t.bold(t.white(callback)) callback = kwargs["callback"] callbackCmds = getCallbackCmds(callback) modules = getPlugins(callbackCmds) if not callbackCmds: header += t.bold(t.red("\nCan't get callbackCmds")) print header return False if not modules: header += t.bold(t.red("\nCan't get Plugins for this callback")) print header return False print header lastCmdStat = True cmdLaunched = list() for cmd in callbackCmds: if not lastCmdStat: break elif cmd not in cmdLaunched: module = loadPlugin((cmd, modules[cmd])) module = module.create(**kwargs) lastCmdStat = module.execute(**kwargs) cmdLaunched.append(cmd) print t.bold(t.yellow("[Finish %s]\n" % exeCmd)) return lastCmdStat
class FoliTable: def __init__(self, name, verbose=False): self.verbose = verbose self.width = 28 self.width_verbose = 48 self.rows = [] self.term = Terminal() if verbose: name = self.normalize(unescape(name), self.width_verbose) else: name = self.normalize(unescape(name), self.width) self.tpl_head_verbose = [ "+------------+--------+--------+-------------------+", "| {headline} |".format(headline=name), "+------------+--------+--------+-------------------+", "| {ti} | {li} | {di} | {destination} |".format( ti=self.term.bold("Time"), li=self.term.bold("Line"), di=self.term.bold("Diff"), destination=self.term.bold( self.normalize("Destination", 17))), "+------------+--------+--------+-------------------+"] self.tpl_line_verbose = "| {time} | {line} | {diff} | {dest} |" self.tpl_endl_verbose = ("+------------+--------+--------" "+-------------------+") self.tpl_head = [ "+------------+--------+--------+", "| {headline} |".format(headline=name), "+------------+--------+--------+", "| {ti} | {li} | {di} |".format( ti=self.term.bold("Time"), li=self.term.bold("Line"), di=self.term.bold("Diff")), "+------------+--------+--------+"] self.tpl_line = "| {time} | {line} | {diff} |" self.tpl_endl = "+------------+--------+--------+" def add_row(self, ftime, line, diff, timediff, dest=None): if timediff <= 0: ftime = self.term.green(self.normalize(ftime, 10)) diff = self.term.green(self.normalize(diff)) else: ftime = self.term.red(self.normalize(ftime, 10)) diff = self.term.red(self.normalize(diff)) line = self.term.bold(self.normalize(line)) if self.verbose: dest = self.normalize(dest, 17) row = self.tpl_line_verbose.format( time=ftime, line=line, diff=diff, dest=dest) else: row = self.tpl_line.format( time=ftime, line=line, diff=diff) self.rows.append(row) def get_row(self, rownr): if rownr < len(self.tpl_head): if self.verbose: return self.tpl_head_verbose[rownr] else: return self.tpl_head[rownr] elif rownr < (len(self.tpl_head)+len(self.rows)): return self.rows[rownr-len(self.tpl_head)] elif rownr == (len(self.tpl_head)+len(self.rows)): if self.verbose: return self.tpl_endl_verbose else: return self.tpl_endl else: if self.verbose: return " "*len(self.tpl_endl_verbose) else: return " "*len(self.tpl_endl) def num_lines(self): return len(self.tpl_head)+len(self.rows)+1 def normalize(self, nstr, length=6): try: nstr = unicode(nstr) encode = True except NameError: if not isinstance(nstr, str): nstr = str(nstr) encode = False if len(nstr) > length: nstr = nstr[0:length-1] nstr = nstr.center(length, " ") if encode: return nstr.encode('utf-8') return nstr
class ProgressiveResult(TextTestResult): """Test result which updates a progress bar instead of printing dots Nose's ResultProxy will wrap it, and other plugins can still print stuff---but without smashing into my progress bar, care of my Plugin's stderr/out wrapping. """ def __init__(self, cwd, total_tests, stream, config=None): super(ProgressiveResult, self).__init__(stream, None, 0, config=config) self._cwd = cwd self._options = config.options self._term = Terminal(stream=stream, force_styling=config.options.with_styling) if self._term.is_a_tty or self._options.with_bar: # 1 in case test counting failed and returned 0 self.bar = ProgressBar(total_tests or 1, self._term, config.options.bar_filled_color, config.options.bar_empty_color) else: self.bar = NullProgressBar() # Declare errorclass-savviness so ErrorClassPlugins don't monkeypatch # half my methods away: self.errorClasses = {} def startTest(self, test): """Update the progress bar.""" super(ProgressiveResult, self).startTest(test) self.bar.update(nose_selector(test), self.testsRun) def _printTraceback(self, test, err): """Print a nicely formatted traceback. :arg err: exc_info()-style traceback triple :arg test: the test that precipitated this call """ # Don't bind third item to a local var; that can create # circular refs which are expensive to collect. See the # sys.exc_info() docs. exception_type, exception_value = err[:2] # TODO: In Python 3, the traceback is attached to the exception # instance through the __traceback__ attribute. If the instance # is saved in a local variable that persists outside the except # block, the traceback will create a reference cycle with the # current frame and its dictionary of local variables. This will # delay reclaiming dead resources until the next cyclic garbage # collection pass. extracted_tb = extract_relevant_tb( err[2], exception_type, exception_type is test.failureException) test_frame_index = index_of_test_frame( extracted_tb, exception_type, exception_value, test) if test_frame_index: # We have a good guess at which frame is the test, so # trim everything until that. We don't care to see test # framework frames. extracted_tb = extracted_tb[test_frame_index:] with self.bar.dodging(): self.stream.write(''.join( format_traceback( extracted_tb, exception_type, exception_value, self._cwd, self._term, self._options.function_color, self._options.dim_color, self._options.editor, self._options.editor_shortcut_template))) def _printHeadline(self, kind, test, is_failure=True): """Output a 1-line error summary to the stream if appropriate. The line contains the kind of error and the pathname of the test. :arg kind: The (string) type of incident the precipitated this call :arg test: The test that precipitated this call """ if is_failure or self._options.show_advisories: with self.bar.dodging(): self.stream.writeln( '\n' + (self._term.bold if is_failure else '') + '%s: %s' % (kind, nose_selector(test)) + (self._term.normal if is_failure else '')) # end bold def _recordAndPrintHeadline(self, test, error_class, artifact): """Record that an error-like thing occurred, and print a summary. Store ``artifact`` with the record. Return whether the test result is any sort of failure. """ # We duplicate the errorclass handling from super rather than calling # it and monkeying around with showAll flags to keep it from printing # anything. is_error_class = False for cls, (storage, label, is_failure) in self.errorClasses.items(): if isclass(error_class) and issubclass(error_class, cls): if is_failure: test.passed = False storage.append((test, artifact)) is_error_class = True if not is_error_class: self.errors.append((test, artifact)) test.passed = False is_any_failure = not is_error_class or is_failure self._printHeadline(label if is_error_class else 'ERROR', test, is_failure=is_any_failure) return is_any_failure def addSkip(self, test, reason): """Catch skipped tests in Python 2.7 and above. Though ``addSkip()`` is deprecated in the nose plugin API, it is very much not deprecated as a Python 2.7 ``TestResult`` method. In Python 2.7, this will get called instead of ``addError()`` for skips. :arg reason: Text describing why the test was skipped """ self._recordAndPrintHeadline(test, SkipTest, reason) # Python 2.7 users get a little bonus: the reason the test was skipped. if isinstance(reason, Exception): reason = reason.message if reason and self._options.show_advisories: with self.bar.dodging(): self.stream.writeln(reason) def addError(self, test, err): # We don't read this, but some other plugin might conceivably expect it # to be there: excInfo = self._exc_info_to_string(err, test) is_failure = self._recordAndPrintHeadline(test, err[0], excInfo) if is_failure: self._printTraceback(test, err) def addFailure(self, test, err): super(ProgressiveResult, self).addFailure(test, err) self._printHeadline('FAIL', test) self._printTraceback(test, err) def printSummary(self, start, stop): """As a final summary, print number of tests, broken down by result.""" def renderResultType(type, number, is_failure): """Return a rendering like '2 failures'. :arg type: A singular label, like "failure" :arg number: The number of tests with a result of that type :arg is_failure: Whether that type counts as a failure """ # I'd rather hope for the best with plurals than totally punt on # being Englishlike: ret = '%s %s%s' % (number, type, 's' if number != 1 else '') if is_failure and number: ret = self._term.bold(ret) return ret # Summarize the special cases: counts = [('test', self.testsRun, False), ('failure', len(self.failures), True), ('error', len(self.errors), True)] # Support custom errorclasses as well as normal failures and errors. # Lowercase any all-caps labels, but leave the rest alone in case there # are hard-to-read camelCaseWordBreaks. counts.extend([(label.lower() if label.isupper() else label, len(storage), is_failure) for (storage, label, is_failure) in self.errorClasses.values() if len(storage)]) summary = (', '.join(renderResultType(*a) for a in counts) + ' in %.1fs' % (stop - start)) # Erase progress bar. Bash doesn't clear the whole line when printing # the prompt, leaving a piece of the bar. Also, the prompt may not be # at the bottom of the terminal. self.bar.erase() self.stream.writeln() if self.wasSuccessful(): self.stream.write(self._term.bold_green('OK! ')) self.stream.writeln(summary)
class Series(object): def __init__(self, player1, player2, numberOfGames, alternateFirstPlayer=True, debug=False, boardWidth=None, boardHeight=None, showVisualization=False, visualizationInterval=.01, clearBoardOnException=False, tournament=None): self.debug = debug self.clearBoardOnException = clearBoardOnException (self.player1, self.player2) = self.players = (player1, player2) if self.player1.name == self.player2.name: self.player1Alias = self.player1.name + ' #1' self.player2Alias = self.player2.name + ' #2' else: self.player1Alias = self.player1.name self.player2Alias = self.player2.name self.numberOfGames = numberOfGames self.player1Wins = 0 self.player2Wins = 0 self.player1.hOffset = 0 self.player2.hOffset = 20 self.showVisualization = showVisualization self.visualizationInterval = visualizationInterval if alternateFirstPlayer: self.games = [Game(self.players[i % 2], self.players[(i + 1) % 2], debug=debug, boardWidth=boardWidth, boardHeight=boardHeight, showVisualization=self.showVisualization, visualizationInterval=self.visualizationInterval) for i in xrange(self.numberOfGames)] else: self.games = [Game(*self.players, debug=debug, boardWidth=boardWidth, boardHeight=boardHeight, showVisualization=self.showVisualization, visualizationInterval=self.visualizationInterval) for i in xrange(self.numberOfGames)] self.player1.currentGame = self.games[0] self.player2.currentGame = self.games[0] self.tournament = tournament self.term = Terminal() if not self.tournament: print self.term.clear @property def player1Losses(self): return self.player2Wins @property def player2Losses(self): return self.player1Wins def start(self): for game in self.games: winner, loser = game.playGame() if winner == self.player1: self.player1Wins += 1 else: self.player2Wins += 1 if self.showVisualization: self.printStats() if game.exception: if self.clearBoardOnException: print self.term.clear print '%s threw an exception' % loser.name print game.exception print if game.exception and self.debug: print print game.traceback print break else: with self.term.location(): self.printStats() if game.exception: print '%s threw an exception' % loser.name print game.exception print if game.exception and self.debug: print print game.traceback print break else: if not self.showVisualization: # For some reason I need to print one more time to keep the final results around # May want to come back and clean this up at some point in the future self.printStats() if self.player1Wins > self.player2Wins: return self.player1, self.player2 elif self.player2Wins > self.player1Wins: return self.player2, self.player1 else: return None def printStats(self): print print print self.term.bold('Current Matchup:') print 'Series games played: %s' % (self.player1Wins + self.player2Wins,) print 'Player1 (%s) series wins: %s' % (self.player1Alias, self.player1Wins) print 'Player2 (%s) series wins: %s' % (self.player2Alias, self.player2Wins) print
from blessings import Terminal term = Terminal() if term.does_styling: with term.location(0, term.height - 1): print 'Progress: [=======> ]' print term.bold('Important stuff')
class Tournament(object): def __init__(self, players, numberOfGames, alternateFirstPlayer=True, debug=False, boardWidth=None, boardHeight=None, showVisualization=False, visualizationInterval=.01, showStatistics=False, clearBoardOnException=False): self.players = players self.numberOfGames = numberOfGames self.alternateFirstPlayer = alternateFirstPlayer self.debug = debug self.boardWidth = boardWidth self.boardHeight = boardHeight self.showVisualization = showVisualization self.visualizationInterval = visualizationInterval self.showStatistics = showStatistics self.clearBoardOnException = clearBoardOnException self.term = Terminal() def run(self): self.results = dict([(player, [{'win': 0, 'lose': 0, 'draw': 0}, []]) for player in self.players]) self.series = [Series(x[0](), x[1](), self.numberOfGames, alternateFirstPlayer=self.alternateFirstPlayer, debug=self.debug, boardWidth=self.boardWidth, boardHeight=self.boardHeight, showVisualization=self.showVisualization, visualizationInterval=self.visualizationInterval, clearBoardOnException=self.clearBoardOnException, tournament=self) for x in combinations(self.players, 2)] random.shuffle(self.series) self.series[0].player1._initializeGameBoard() self.series[0].player2._initializeGameBoard() self.displayLeaderBoard(nextGameIndex=1) for idx, series in enumerate(self.series): if self.showVisualization: print self.term.clear self.series[0].player1._initializeGameBoard() self.series[0].player2._initializeGameBoard() series.printStats() self.displayLeaderBoard(nextGameIndex=idx + 1) result = series.start() if result is not None: self.results[type(result[0])][0]['win'] += 1 self.results[type(result[1])][0]['lose'] += 1 self.results[type(result[0])][1].append(type(result[1]).__name__) else: # A null result means we got a draw self.results[type(result[0])][0]['draw'] += 1 self.results[type(result[1])][0]['draw'] += 1 print self.displayLeaderBoard(nextGameIndex=idx + 1) print self.term.move(0, 0) print self.term.clear self.displayLeaderBoard() print print self.finalResults() print def displayLeaderBoard(self, nextGameIndex=None): rankings = sorted(self.results.items(), key=lambda x: (-x[1][0]['win'], sum(x[1][0].values()))) data = [] for idx, ranking in enumerate(rankings): data.append(('%s: %s' % (idx + 1, ranking[0].__name__), ranking[1][0]['win'], ranking[1][0]['lose'], ranking[1][0]['draw'], sum(ranking[1][0].values()))) table = tabulate(data, headers=['Player', 'Wins', 'Losses', 'Draws', 'GP']) if nextGameIndex is not None and nextGameIndex < len(self.series): print self.term.bold('Next matchup:') + ' %s v. %s' % (self.series[nextGameIndex].player1.name, self.series[nextGameIndex].player2.name) print print self.term.bold('LeaderBoard') print table def finalResults(self): rankings = sorted(self.results.items(), key=lambda x: -x[1][0]['win']) for idx, ranking in enumerate(rankings): print '%s: %s' % (idx + 1, ranking[0].__name__) print ' with wins against %s' % ranking[1][1]
continue else: hashes.add(h) unique.append(p) duplicates = len(ps)-len(hashes) if duplicates > 0: print(INFORMATIONAL + "Ignoring "+ str(duplicates) + " duplicate protocols (identical hashes)") return unique VERSION = "Tamarin Tester v1.0" DESCRIPTION = "tamarin-tester is a tool for testing the correctness of tamarin-prover builds by comparing their output to known-good builds. For a more comprehensive overview, consult the README distributed with this program. In general, you may run tests against benchmark files or generate these benchmark files yourself. Authored by Dennis Jackson, Computer Science Dept, University of Oxford." TERMINAL = Terminal() ERROR = TERMINAL.bold(TERMINAL.red("ERROR ")) INFORMATIONAL = TERMINAL.bold(TERMINAL.blue("INFORMATIONAL ")) WARNING = TERMINAL.yellow(TERMINAL.bold("WARNING ")) CHECK_TIMEOUT= TERMINAL.red(TERMINAL.bold("CHECK TIMEOUT ")) MALFORMED= TERMINAL.bold(TERMINAL.red("MALFORMED ")) BENCH_TIMEOUT= TERMINAL.red(TERMINAL.bold("BENCH TIMEOUT ")) NO_LEMMAS= TERMINAL.yellow(TERMINAL.bold("NO LEMMAS ")) INCORRECT= TERMINAL.bold(TERMINAL.red("\t INCORRECT: ")) STEPSIZE_INC= TERMINAL.bold(TERMINAL.yellow("\t STEPSIZE INC: ")) STEPSIZE_DEC= TERMINAL.bold(TERMINAL.yellow("\t STEPSIZE DEC: ")) TIMEOUT= TERMINAL.bold(TERMINAL.red("\t TIMEOUT ")) OVERTIME= TERMINAL.yellow(TERMINAL.bold("OVERTIME ")) NO_BENCHMARK= TERMINAL.yellow(TERMINAL.bold("NO BENCHMARK "))
class testGroup(object): """TestGroup, group a number of testUnit, exec them and print the results""" def __init__(self, name="", terminal=None, prefix="", verbose=False, align=0): self._tests = [] self.name = name self.t = terminal self.prefix = prefix (self.t) if self.t == None: self.t = Terminal() self.results = [] self.status_modules = { "success": 0, "total": 0, "warning": 0, "critical": 0, "failure": 0 } self.success_text = self.t.green("success") self.failure_text = self.t.bright_red("failure") self.warning_text = self.t.bright_yellow("warning") self.critical_text = self.t.white_on_red("critical") self.verbose = verbose self.align = align def addTest(self, testUnit): self._tests.append(testUnit) return self def test(self): "Execute all tests, some options might exist at some point" module_success, module_total = 0, 0 print(self.prefix + "+ Executing test group " + self.pretty_group(self.name)) oldprefix = self.prefix self.prefix += "| " self.results = [] for test in self._tests: try: list_status, total, log_results = self.print_result( test.test()) except Exception as e: print( self.t.bright_red( "[ERROR] An unhandled error occured during the execution of the tests" )) raise (e) # for l in e: # print(l) list_status, total, log_results = self.print_result([]) print(self.pretty_subtests(test.name, list_status, total)) if list_status["success"] + list_status["warning"] == total: self.status_modules["success"] += 1 self.status_modules["total"] += 1 for log in log_results: print(log) self.results.append([self, SUCCESS_STATUS, ""]) self.prefix = oldprefix print( self.pretty_group_result(self.status_modules, self.status_modules["total"])) return self.results def get_status(self): "Get the status of every module, if no test was run, should return an empty dict" return self.status_modules def print_result(self, table): "Get the array of success/failures and print according to the options (still none yet)" total = len(table) success = 0 results_array = [] nb = 0 list_status = {"success": 0, "failure": 0, "warning": 0, "critical": 0} for item, status, infos in table: nb += 1 if status == SUCCESS_STATUS: list_status["success"] += 1 elif status == WARNING_STATUS: list_status["warning"] += 1 elif status == CRITICAL_STATUS: list_status["critical"] += 1 else: list_status["failure"] += 1 if self.verbose or status != SUCCESS_STATUS: results_array.append( self.pretty_result(status, nb, item, infos)) return list_status, total, results_array def pretty_group_result(self, module_status, total): "Prettyfying the result of the batch of tests" bloc = self.prefix + "+ Done " return bloc + self.pretty_group(self.name) + self.pretty_dots( bloc, len(self.name)) + self.pretty_successrate( module_status, total) def pretty_name(self, item): "Just a pretty way of showing the name of a test" try: return item.__name__.strip("<>") except: return str(item) def pretty_subtests(self, name, success, total): "Pretty way of showing the result of the group of tests" bloc = self.prefix + "testing " + self.pretty_test(name) return bloc + self.pretty_dots(bloc) + self.pretty_successrate( success, total) def pretty_result(self, status, nb, item, infos): "Just a pretty way of showing the result of one test" bloc = self.prefix + " * " + " [" + str(nb) + "] " + self.pretty_name( item) if status == CRITICAL_STATUS: pbloc = self.prefix + " * " + " [" + str( nb) + "] " + self.t.bold_bright_red(self.pretty_name(item)) else: pbloc = bloc return pbloc + self.pretty_dots(bloc) + self.pretty_status( status) + self.pretty_info(infos) def pretty_dots(self, bloc, padding=0): lenbloc = len(bloc) + padding if (self.align > lenbloc + 2): dots = "." * (self.align - lenbloc) else: dots = ".." return dots def pretty_info(self, infos): "Prettyfy the additional infos" if infos == "": return "" return self.t.italic(" (" + str(infos) + ")") def pretty_status(self, status): "Prettyfy the status of the test" if status == SUCCESS_STATUS: return self.success_text elif status == FAILURE_STATUS: return self.failure_text elif status == WARNING_STATUS: return self.warning_text else: return self.critical_text def pretty_group(self, name): "Prettify the name of the testGroup" return self.t.bold(name) def pretty_test(self, test): "Prettify the name of the testUnit" return test def pretty_successrate(self, success, total): warnings = "" if success["success"] == total: wrap = self.t.green txt = self.success_text elif success["success"] + success["warning"] == total: wrap = self.t.yellow txt = self.warning_text warnings = " ({} warnings)".format(str(success["warning"])) elif success["critical"] != 0: wrap = self.t.white_on_red txt = self.critical_text else: wrap = self.t.bright_red txt = self.failure_text return wrap(txt + " [" + str(success["success"] + success["warning"]) + "/" + str(total) + "]" + warnings) def __str__(self): return self.name
"email": "*****@*****.**", "password": "******", "logins": 0 } user_data2 = \ { "doctype": "learn", "username": "******", "name": "Xavier Smith", "email": "*****@*****.**", "password": "******", "logins": 0 } print t.bold("Set 2 User Docs") print # initialize the documents cb.set(user_data1["email"], 0, 0, json.dumps(user_data1)) cb.set(user_data2["email"], 0, 0, json.dumps(user_data2)) # retrieve the document and output print t.bold("Retrieve Doc and Inspect CAS") print kv = cb.get(user_data1["email"]) print kv print "cas = " + str(kv[1]) print
def display_results(hit, etymology): """Render results to STDOUT, with pretty whitespace.""" t = Terminal() print(t.bold(hit)) print(fill(etymology, width=t.width))
from blessings import Terminal term = Terminal() location = (0,1) with term.location(location[0], location[1]): print 'This is', term.bold('pretty!')
#!/usr/bin/python3 from blessings import Terminal t = Terminal() print(t.clear()) print(t.bold("Hi, There!!")) print(t.move_down) print(t.bold_red_on_bright_green('It hurts my eyes!')) print(t.move_down+t.bold_underline_black_on_bright_yellow('It hurts my eyes! blinking')) print(t.move_down) print("Terminal Width", t.width) print("Terminal height", t.height) print(t.move_down) print(t.move_down) print("one line for Terminal Width and hight",t.reverse, t.width, t.height) with t.location(20, t.height - 1): print(t.reverse+t.blink('Blinking in REVERSE!!!!! '))
class ProgressiveResult(TextTestResult): """Test result which updates a progress bar instead of printing dots Nose's ResultProxy will wrap it, and other plugins can still print stuff---but without smashing into my progress bar, care of my Plugin's stderr/out wrapping. """ def __init__(self, cwd, total_tests, stream, config=None): super(ProgressiveResult, self).__init__(stream, None, 0, config=config) self._cwd = cwd self._options = config.options self._term = Terminal(stream=stream, force_styling=config.options.with_styling) if self._term.is_a_tty or self._options.with_bar: # 1 in case test counting failed and returned 0 self.bar = ProgressBar(total_tests or 1, self._term, config.options.bar_filled_color, config.options.bar_empty_color) else: self.bar = NullProgressBar() # Declare errorclass-savviness so ErrorClassPlugins don't monkeypatch # half my methods away: self.errorClasses = {} def startTest(self, test): """Update the progress bar.""" super(ProgressiveResult, self).startTest(test) self.bar.update(nose_selector(test), self.testsRun) def _printTraceback(self, test, err): """Print a nicely formatted traceback. :arg err: exc_info()-style traceback triple :arg test: the test that precipitated this call """ # Don't bind third item to a local var; that can create # circular refs which are expensive to collect. See the # sys.exc_info() docs. exception_type, exception_value = err[:2] extracted_tb = extract_relevant_tb( err[2], exception_type, exception_type is test.failureException) test_frame_index = index_of_test_frame(extracted_tb, exception_type, exception_value, test) if test_frame_index: # We have a good guess at which frame is the test, so # trim everything until that. We don't care to see test # framework frames. extracted_tb = extracted_tb[test_frame_index:] with self.bar.dodging(): self.stream.write(''.join( format_traceback(extracted_tb, exception_type, exception_value, self._cwd, self._term, self._options.function_color, self._options.dim_color, self._options.editor))) def _printHeadline(self, kind, test, is_failure=True): """Output a 1-line error summary to the stream if appropriate. The line contains the kind of error and the pathname of the test. :arg kind: The (string) type of incident the precipitated this call :arg test: The test that precipitated this call """ if is_failure or self._options.show_advisories: with self.bar.dodging(): self.stream.writeln( '\n' + (self._term.bold if is_failure else '') + '%s: %s' % (kind, nose_selector(test)) + (self._term.normal if is_failure else '')) # end bold def _recordAndPrintHeadline(self, test, error_class, artifact): """Record that an error-like thing occurred, and print a summary. Store ``artifact`` with the record. Return whether the test result is any sort of failure. """ # We duplicate the errorclass handling from super rather than calling # it and monkeying around with showAll flags to keep it from printing # anything. is_error_class = False for cls, (storage, label, is_failure) in self.errorClasses.iteritems(): if isclass(error_class) and issubclass(error_class, cls): if is_failure: test.passed = False storage.append((test, artifact)) is_error_class = True if not is_error_class: self.errors.append((test, artifact)) test.passed = False is_any_failure = not is_error_class or is_failure self._printHeadline(label if is_error_class else 'ERROR', test, is_failure=is_any_failure) return is_any_failure def addSkip(self, test, reason): """Catch skipped tests in Python 2.7 and above. Though ``addSkip()`` is deprecated in the nose plugin API, it is very much not deprecated as a Python 2.7 ``TestResult`` method. In Python 2.7, this will get called instead of ``addError()`` for skips. :arg reason: Text describing why the test was skipped """ self._recordAndPrintHeadline(test, SkipTest, reason) # Python 2.7 users get a little bonus: the reason the test was skipped. if reason and self._options.show_advisories: with self.bar.dodging(): self.stream.writeln(reason) def addError(self, test, err): # We don't read this, but some other plugin might conceivably expect it # to be there: excInfo = self._exc_info_to_string(err, test) is_failure = self._recordAndPrintHeadline(test, err[0], excInfo) if is_failure: self._printTraceback(test, err) def addFailure(self, test, err): super(ProgressiveResult, self).addFailure(test, err) self._printHeadline('FAIL', test) self._printTraceback(test, err) def printSummary(self, start, stop): """As a final summary, print number of tests, broken down by result.""" def renderResultType(type, number, is_failure): """Return a rendering like '2 failures'. :arg type: A singular label, like "failure" :arg number: The number of tests with a result of that type :arg is_failure: Whether that type counts as a failure """ # I'd rather hope for the best with plurals than totally punt on # being Englishlike: ret = '%s %s%s' % (number, type, 's' if number != 1 else '') if is_failure and number: ret = self._term.bold(ret) return ret # Summarize the special cases: counts = [('test', self.testsRun, False), ('failure', len(self.failures), True), ('error', len(self.errors), True)] # Support custom errorclasses as well as normal failures and errors. # Lowercase any all-caps labels, but leave the rest alone in case there # are hard-to-read camelCaseWordBreaks. counts.extend([(label.lower() if label.isupper() else label, len(storage), is_failure) for (storage, label, is_failure) in self.errorClasses.itervalues() if len(storage)]) summary = (', '.join(renderResultType(*a) for a in counts) + ' in %.1fs' % (stop - start)) # Erase progress bar. Bash doesn't clear the whole line when printing # the prompt, leaving a piece of the bar. Also, the prompt may not be # at the bottom of the terminal. self.bar.erase() self.stream.writeln() if self.wasSuccessful(): self.stream.write('OK! ') self.stream.writeln(summary)
#!/usr/bin/env python3 #Defining Functions #Written by Homer Walden #Import files from blessings import Terminal t = Terminal() #set variable t for Terminal file print(t.clear()) #clears the text print(t.bold('Hi there!')) #prints bold test print(t.move_down) #moves cursor down one line print(t.bold_red_on_bright_green('It hurts my eyes!')) #print in bold and green print(t.move_down+t.bold_underline_black_on_yellow('Look! A 1997 web page! No, the font would have to be blinking')) print(t.move_down) print(" Terminal width: ",t.width) print(" Terminal height: ",t.height) print(t.move_down+"A one-liner way to show terminal width and height",t.reverse,t.width,"by",t.height," ") #combine height and width methods into one line with t.location(20, t.height - 1): print(t.reverse + t.blink('This is at the bottom and printed in REVERSE.'))
#!/usr/bin/env python from plumbum.cmd import cat, csvfix, in2csv, sed, rm from blessings import Terminal import os import glob import csv import re # Setup the terminal object for blessings term = Terminal() # Get setup data_path = "../data" database_file_name = "piction" print term.bold("Processing data for the Digital Scrapbook") # Cleanup from last time print rm("-rf", database_file_name + ".csv") # Get all the sheets into CSVs print term.yellow("Extracting the CSVs") sheets = [ "1-Anza", "2-Cleve", "13-SDCst", "19-L.A.", "7-Moj", "12-Bern", "3-Color",
print t.clear() time_b = mc.stats() hits_a = int(time_a['get_hits']) hits_b = int(time_b['get_hits']) misses_a = int(time_a['get_misses']) misses_b = int(time_b['get_misses']) print ' Efficiency Requests' try: requests = "{0:>10,}".format((hits_b - hits_a) + (misses_b - misses_a)) efficiency = "{:>10.1%}".format(percent_change_in_interval(hits_a, hits_b, misses_a, misses_b)) except: efficiency = " ----" print 'Interval: ', t.bold(efficiency), t.bold(requests) try: requests = "{0:>10,}".format((hits_b - hits_0) + (misses_b - misses_0)) efficiency = "{:>10.1%}".format(percent_change_in_interval(hits_0, hits_b, misses_0, misses_b)) except: efficiency = " ----" print 'Cumulative: ', t.bold(efficiency), t.bold(requests) try: requests = "{0:>10,}".format(hits_b + misses_b) efficiency = "{:>10.1%}".format(percent_change_in_interval(0, hits_b, 0, misses_b)) except: efficiency = " ----"
#!/usr/bin/env python3 from blessings import Terminal t = Terminal() print(t.clear()) print(t.bold('Hi there!')) print(t.move_down) print(t.bold_red_on_bright_green('It hurts my eyes!')) print(t.move_down + t.bold_underline_black_on_yellow( 'Look! a 1997 web page! No, the font would have to be blinking')) print(t.move_down) print(" Terminal width: ", t.width) print(" Terminal height: ", t.height) print(t.move_down + "A one-liner way to show terminal width and height", t.reverse, t.width, "by", t.height, " ") with t.location(20, t.height - 1): print(t.reverse + t.blink('This is at thebottom and printed in REVERSE. '))
#!/usr/bin/env python3 from blessings import Terminal t = Terminal() print(t.clear()) print(t.bold("Hi there!")) print(t.move_down) print(t.bold_red_on_bright_green("It hurts my eyes!")) print(t.move_down + t.bold_underline_black_on_yellow( "Look! A 1997 web page! No, the font would have to be blinking!")) print(t.move_down) print(" Terminal width: ", t.width) print(" Terminal height: ", t.height) print(t.move_down + "A one-liner way to show terminal width and height", t.reverse, t.width, "by", t.height, " ") with t.location(20, t.height - 1): print(t.reverse + t.blink("This is at the bottom and printed in REVERSE."))
"-d", args['mcu'], "-F", args['freq'], "-W", "0xC6,/tmp/avr/serial", "--file", args['file'] ], stdout=PIPE, bufsize=1, close_fds=ON_POSIX ) print "simulator starting" msg = "" term.enter_fullscreen() print term.clear term.move(0, 0) print term.bold('= Mechane Simulation =!') try: while True: print term.clear # get output from simulation try: msg += serial.get_nowait() except Empty: pass with term.location(0, 2): print "serial: " + msg bot.m1.rotation += math.pi/8
s = f.read() print (s), print ("") pause_for_logo = raw_input('Press enter to continue..............') create_new_hero = raw_input("Do you want to create a new hero? Enter 'Y' or 'N' ") create_new_hero.upper() if create_new_hero == "Y": hero_create = raw_input("New Hero Name: ") new_hero(hero_create) os.system(['clear','cls'][os.name == 'nt']) print term.bold("*****************************************") print term.bold("************ Choose Your Hero ***********") print term.bold('*****************************************') print load_hero_list = open("herolist.txt", "r") hero_list_display = load_hero_list.read() print hero_list_display login_name = raw_input("Choose Hero: ") load_hero = shelve.open(login_name, writeback=True) game_loop = 1 hero_data = load_hero[login_name] while game_loop != 0: os.system(['clear','cls'][os.name == 'nt']) with term.location(): print term.blue_on_yellow + term.move(1, 60) + (login_name) + term.normal