我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用termcolor.cprint()。
def run_score(self): """ Run checks on self.files, printing raw percentage to stdout. """ diffs = 0 lines = 0 for file in self.files: try: results = self._check(file) except Error as e: termcolor.cprint(e.msg, "yellow", file=sys.stderr) continue diffs += results.diffs lines += results.lines try: print(1 - diffs / lines) except ZeroDivisionError: print(0.0)
def print_restricted(strings, template, spacing, color=None): """ Prints a list of strings spaced out on the screen according to an accompanying template list. Output can be colored via cprint and the color variable. """ string_list = [] for each in zip(strings, template, spacing): segment = each[1].format(each[0][:each[2]], width=each[2]) string_list.append(segment) for each in string_list: if color == None: print(each, end='') else: cprint(each, color, end='')
def main(): """Program?n ana döngüsü, oyunun çal??mas?ndan yükümlü""" tekrar_edecek_mi = True dosyay_kontrol_et_yoksa_olustur() cprint("Merhaba, Adam Asmacaya ho?geldiniz.", color="cyan", on_color="on_magenta", attrs=["bold"]) cprint("Yard?m: Oyun s?ras?nda quit diyerek ç?kabilirsiniz", color="cyan", on_color="on_magenta", attrs=["bold"]) cprint("-"*30, color="cyan", on_color="on_magenta", attrs=["bold"]) skor_tablosunu_goster() kullanici_kontrol() while tekrar_edecek_mi: oyun_hazirlik() oyun_dongusu() oyun_sonucu() if input("Devam?(e/h) ").lower() == "h": tekrar_edecek_mi = False cprint("Gidiyor gönlümün efendisi...", color="red", on_color="on_blue")
def run(self): #resetEngines() if not self.check(): return self.set_arch() #enableSymbolicEngine(True) self.optimization() self.load_binary() self.set_regs() self.load_stack() # make Symbolic if self.symbolized_argv: self.symbolize_argv() self.symbolize_memory() # symbolic execution if not self.emulate(self.registers[Arch().pc_reg]): print(cprint("No answer is found!!!", 'red')) # Commands
def get_arguments(): """Get Arguments command line.""" parser = argparse.ArgumentParser( description=cprint(figlet_format("ZeUs!", font="starwars"), "green", attrs=["bold"]), prog="zeus") parser.add_argument("--project", "-p", help="Creating project.", type=str, default="") parser.add_argument("--module", "-m", help="Creating module.", nargs=2) parser.add_argument("--template", "-t", help="Creating template.", nargs=2) parser.add_argument("--author", "-a", help="Author of project (default: %(default)s).", type=str, default="Lab804") parser.add_argument("--domain", "-do", help="Domain, (default: %(default)s)", type=str, default="lab804.com.br") parser.add_argument("--debug", "-d", help="Debug mode.", type=bool, default=False), parser.add_argument("--version", "-v", action="version", version="%(prog)s 0.1.2") args = parser.parse_args() return args
def c(msg, colour): try: from termcolor import colored, cprint p = lambda x: cprint(x, '%s' % colour) return p(msg) except: print (msg)
def log_print(text, color=None, on_color=None, attrs=None): if cprint is not None: cprint(text, color=color, on_color=on_color, attrs=attrs) else: print(text)
def print_stack_trace(): """ Prints the stack trace of the programme when an error occurred :return: None """ try: ct = StringIO() ct.seek(0) traceback.print_exc(file=ct) except: traceback.print_exc(file=sys.stderr) else: tc.cprint("\nERROR:", "red") tc.cprint(str(ct.getvalue()), "yellow")
def run_diff(self): """ Run checks on self.files, printing diff of styled/unstyled output to stdout. """ files = tuple(self.files) # Use same header as more. header, footer = (termcolor.colored("{0}\n{{}}\n{0}\n".format( ":" * 14), "cyan"), "\n") if len(files) > 1 else ("", "") for file in files: print(header.format(file), end="") try: results = self._check(file) except Error as e: termcolor.cprint(e.msg, "yellow", file=sys.stderr) continue # Display results if results.diffs: print() print(*self.diff(results.original, results.styled), sep="\n") print() conjunction = "And" else: termcolor.cprint("Looks good!", "green") conjunction = "But" if results.diffs: for type, c in sorted(self._warn_chars): color, verb = ("on_green", "insert") if type == "+" else ("on_red", "delete") termcolor.cprint(c, None, color, end="") termcolor.cprint(" means that you should {} a {}.".format( verb, "newline" if c == "\\n" else "tab"), "yellow") if results.comment_ratio < results.COMMENT_MIN: termcolor.cprint("{} consider adding more comments!".format(conjunction), "yellow") if (results.comment_ratio < results.COMMENT_MIN or self._warn_chars) and results.diffs: print()
def log_print(text, color=None, on_color=None, attrs=None): if cprint is not None: cprint(text, color=color, on_color=on_color, attrs=attrs) else: print(text) # hyper-parameters # ------------
def cprint(*args, **kwargs): print(*args)
def harf_al(): """Kullan?c?dan bir harf al?r, alana kadar gerekirse hata verir, birisi quit yazarsa program? kapat?r""" devam = True while devam: harf = input("Bir harf giriniz: ") if harf.lower() == "quit": cprint("Gidiyor gönlümün efendisi...", color="red", on_color="on_blue") exit() elif len(harf) == 1 and harf.isalpha() and harf not in gorunen_kelime: devam = False else: cprint("Hatal? Giri?", color="red", on_color="on_grey") # noinspection PyUnboundLocalVariable return harf.lower()
def oyun_dongusu(): """Oyunun ana döngüsü, harf al?r, tutarsa görünen karakterler listesi güncellenir, tutmazsa can azalt?l?r, ve bu can bitene kadar ya da kelime bilinene kadar devam eder...""" global gorunen_kelime, can while can > 0 and secilen_kelime != "".join(gorunen_kelime): cprint("kelime: " + "".join(gorunen_kelime), color="cyan", attrs=["bold"]) cprint("can : <" + "?" * can + " " * (5 - can) + ">", color="cyan", attrs=["bold"]) girilen_harf = harf_al() pozisyonlar = harf_kontrol(girilen_harf) if pozisyonlar: for p in pozisyonlar: gorunen_kelime[p] = girilen_harf else: can -= 1
def skor_tablosunu_goster(): """Skor tablosunu gösterir""" veri = ayar_oku() cprint("|Skor\t\tKullan?c?|", color="white", on_color="on_grey") cprint("|------------------------|", color="white", on_color="on_grey") for skor, kullanici in veri["skorlar"]: cprint("|"+str(skor) +"\t\t"+ kullanici+" "*(9-len(kullanici))+"|", color="white", on_color="on_grey") cprint("|------------------------|", color="white", on_color="on_grey")
def oyun_sonucu(): """Oyun bitti?inde kazan?p kazanamad???m?z? ekrana yazar.""" if can > 0: cprint("Kazand?n?z", color="yellow", on_color="on_red") skor_tablosunu_guncelle() else: cprint("Kaybettiniz", color="red", on_color="on_yellow") skor_tablosunu_goster()
def print_green(msg): cprint(msg, 'green')
def print_red(msg): cprint(msg, 'red')
def verbose(msg): if VERBOSE: cprint("==> hokusai exec `%s`" % msg, 'yellow') return msg
def print_symbolic_variables(self): for address, size in self.symbolized_memory: answer = "" for index in range(size): answer += chr( TritonContext.getSymbolicMemoryValue( MemoryAccess(address + index, CPUSIZE.BYTE))) cprint("%s-%s: %s" % (hex(address), hex(address + size), repr(answer)), 'green')
def invoke(self, arg, from_tty): args = parse_arg(arg) if args[0] == 'argv': cprint("Automatically symbolize argv", 'green') Symbolic().symbolized_argv = True elif args[0] == 'memory' and len(args) == 3: address, size = map(lambda x: int(x, 0), args[1:]) cprint("Set symbolized memory %s-%s" % (hex(address), hex(address + size)), 'green') Symbolic().symbolized_memory.append([address, size]) elif args[0] == 'register': Symbolic().symbolized_registers.append(args[1])
def invoke(self, arg, from_tty): args = parse_arg(arg) if len(args) == 1: target_address = int(args[0], 0) cprint("Set target address = %s" % hex(target_address), 'green') Symbolic().target_address = target_address
def help_command_interface(): cmd_cmd = lambda x: cprint(x, 'grey', 'on_white') cmd_cmd('Commands:') cmd_test = colored('test', attrs=['underline']) print(cmd_test + " {performs a test}") cmd_calc = colored('calc', attrs=['underline']) print(cmd_calc + " {A calculator}") cmd_clr = colored('clr', attrs=['underline']) print(cmd_clr + " {clears console}") cmd_rps = colored('rps', attrs=['underline']) print(cmd_rps + " {Rock Paper Scissors game}") cmd_screen = colored('screen', attrs=['underline']) print(cmd_screen + " {opens a window}") cmd_cat = colored('cat', attrs=['underline']) print(cmd_cat + " {opens a pic of the cutes kitty cat you'll ever see}") cmd_numgen = colored('numgen', attrs=['underline']) print(cmd_numgen + " {Generates random numbers}") cmd_passgen = colored('passgen', attrs=['underline']) print(cmd_passgen + " {Generates a random password}") cmd_chpass = colored('chpass', attrs=['underline']) print(cmd_chpass + " {Change your login password}") cmd_guess = colored('guess', attrs=['underline']) print(cmd_guess + " {Guess the number}") cmd_snow = colored('snow', attrs=['underline']) print(cmd_snow + " {Shitty falling snow}") cmd_datingsim = colored('datingsim', attrs=['underline']) print(cmd_datingsim + " {A dating simulator}") cmd_weather = colored('weather', attrs=['underline']) print(cmd_weather + " {Check the weather}") cmd_soon = lambda x: cprint(x, 'grey', 'on_white') cmd_soon('- More commands soon -')
def print_bucket_status(bucket, status): # Public access exists if status == "S3WebSite": print colored("Bucket: "+ bucket, color="yellow"), " - Found index.html, most probably S3 static web hosting is enabled" elif status == "S3WebSite!": print colored("Bucket: "+ bucket, color="yellow"), " - S3 static web hosting is enabled on the bucket" elif status == "NoSuchKey": print colored("Bucket: "+ bucket, color="red"), " - Bucket exists, publicly available and no S3 static web hosting, most probably misconfigured! " elif status == "AllUsersAccess" or status == "AllAuthUsersAccess": print colored("Bucket: "+ bucket, color="red"), " - Bucket exists and publicly ( "+ status+ " ) "+ " available. Reason: Bucket ACL ! " elif "s3:" in status: print colored("Bucket: "+ bucket, color="red"), " - Bucket exists and publicly ( "+ status+ " ) "+ " available. Reason: Bucket Policy ! " # Can't check due to the access restrictions: elif status == "AccessDenied2ACL" or status == "AccessDenied2Policy": print colored("Bucket: "+ bucket, color="yellow"), " - Bucket exists, but can't verify policy or ACL due to the: "+ status # No public acess elif status == "AccessDenied" or status == "NoSuchBucketPolicy" or status == "NoPublicAccess": print colored("Bucket: "+ bucket, color="green"), " - No public access detected" # No bucket - no problem elif status == "NoSuchBucket": print colored("Bucket: "+ bucket, color="green"), " - The specified bucket does not exist" # Can't really verify due to the API Error elif status == "Can'tVerify" or status == "InvalidRequest": print colored("Bucket: "+ bucket, color="yellow"), "- Can't really verify due to the API Error" else: cprint("Bucket: "+ bucket+ "----"+ status, "yellow") return
def success(string): termcolor.cprint(string, 'green')
def fail(string): termcolor.cprint(string, 'red')
def warning(string): termcolor.cprint(string, 'yellow') # Model Timer
def c(msg, colour): try: from termcolor import colored, cprint p = lambda x: cprint(x, '%s' % colour) return p(msg) except: print(msg)
def create_img(self, base_img_path, img_path): cmd = ["qemu-img create", "-b {}".format(base_img_path), "-f qcow2", "{}".format(img_path)] #cprint("["+self.__host_name+"][QEMU]: creating VM image.", self.__output_color) #print(" ".join(cmd)) return cmd
def checkpoint_vm(self): cprint("["+self.__host_name+"][QEMU]: checkpointing VM.", self.__output_color) self.__pexpect_child.expect('(qemu)') sendline('savevm bee_saved')
def restore_vm(self): cprint("["+self.__host_name+"][QEMU]: restoringing VM.", self.__output_color) self.__pexpect_child.expect('(qemu)') sendline('loadvm bee_saved')
def print_f_score(output, target): """returns: p<recision>, r<ecall>, f<-score>, {"TP", "p", "TP_plus_FP"} """ p, r, TP, TP_plus_FN, TP_plus_FP = precision_recall(output, target) f = F_score(p, r) # cprint("Label: " + c((" " + str(10))[-5:], 'red') + # "\tPrec: " + c(" {:.1f}".format(0.335448 * 100)[-5:], 'green') + '%' + # " ({:d}/{:d})".format(1025, 1254).ljust(14) + # "Recall: " + c(" {:.1f}".format(0.964 * 100)[-5:], 'green') + "%" + # " ({:d}/{:d})".format(15, 154).ljust(14) + # "F-Score: " + (c(" {:.1f}".format(0.5 * 100)[-5:], "green") + "%") # ) for label in f.keys(): cprint("Label: " + c((" " + str(label))[-5:], 'red') + "\tPrec: " + c(" {:.1f}".format(p[label] * 100)[-5:], 'green') + '%' + " ({:d}/{:d})".format((TP[label] if label in TP else 0), TP_plus_FP[label]).ljust(14) + "Recall: " + c(" {:.1f}".format((r[label] if label in r else 0) * 100)[-5:], 'green') + "%" + " ({:d}/{:d})".format((TP[label] if label in TP else 0), TP_plus_FN[label]).ljust(14) + "F-Score: " + (" N/A" if f[label] is None else (c(" {:.1f}".format(f[label] * 100)[-5:], "green") + "%")) ) # return p, r, f, _
def generate(self): """Generate Project.""" logger.debug("Starting generating project...") start = time.time() # Config self._config() # Extensions self._extensions() # App self._app() # Manage self._manage() # License self._license() # Readme self._readme() # Fabfile self._fabfile() # Uwsgi self._uwsgi() # Conf files Nginx Supervidor self._config_files() # Std. Modules self.module.ger_std_modules() end = time.time() - start cprint("=" * 55, "green", attrs=["bold"]) logger.info("[ \u0231 ] Finishing: %f sec." % end)
def emulate(self, pc): while pc: # Fetch opcodes opcode = TritonContext.getConcreteMemoryAreaValue(pc, 16) # Create the Triton instruction instruction = Instruction() instruction.setOpcode(opcode) instruction.setAddress(pc) # Process if (not TritonContext.processing(instruction)): print("Current opcode is not supported.") self.log(instruction) if TritonContext.isRegisterSymbolized(Arch().triton_pc_reg): pc_expr = TritonContext.getSymbolicExpressionFromId( TritonContext.getSymbolicRegisterId(Arch().triton_pc_reg)) pc_ast = astCtxt.extract(Arch().reg_bits - 1, 0, pc_expr.getAst()) # Define constraint cstr = astCtxt.equal(pc_ast, astCtxt.bv(self.target_address, Arch().reg_bits)) model = TritonContext.getModel(cstr) if model: cprint('Got answer!!!', 'green') for sym_id, sym_model in model.items(): value = sym_model.getValue() TritonContext.setConcreteSymbolicVariableValue( TritonContext.getSymbolicVariableFromId(sym_id), value) cprint('Symbolic variable %02d = %02x (%c)' % (sym_id, value, chr(value)), 'green') if click.confirm('Inject back to gdb?', default=True): self.inject_to_gdb() return True # Next pc = TritonContext.buildSymbolicRegister( Arch().triton_pc_reg).evaluate()
def check_auth_bucket(bucket_name): # Let's check S3 static web site hosting status try: website_status =s3.get_bucket_website(Bucket=bucket_name) bucket_status_code = "S3WebSite!" return bucket_status_code except ClientError as ex: bucket_status_code = ex.response['Error']['Code'] # Let's try to get bucket ACL and Policy # ACL try: bucket_acl = s3.get_bucket_acl(Bucket=bucket_name) for grant in bucket_acl["Grants"]: if grant["Grantee"]["Type"] == "Group" and "AllUsers" in grant["Grantee"].get("URI"): bucket_status_code = "AllUsersAccess" return bucket_status_code elif grant["Grantee"]["Type"] == "Group" and "AuthenticatedUsers" in grant["Grantee"].get("URI"): bucket_status_code = "AllAuthUsersAccess" return bucket_status_code except ClientError as ex: if ex.response['Error']['Code'] == "AccessDenied": bucket_status_code = "AccessDenied2ACL" else: bucket_status_code ="Can'tVerify" # cprint ("Weird"+ str(ex.response['Error']), "red") #Policy try: bucket_policy = s3.get_bucket_policy(Bucket=bucket_name) bucket_policy_j = json.loads(bucket_policy["Policy"]) for statement in bucket_policy_j["Statement"]: if (statement.get("Condition") is None and statement["Effect"] == "Allow" and ("'*'" in str(statement["Principal"]) or statement["Principal"] == "*")): bucket_status_code = str(statement["Action"]) return bucket_status_code # Policy exists but not allow public access bucket_status_code = "NoPublicAccess" except ClientError as ex: if ex.response['Error']['Code'] == "NoSuchBucketPolicy": bucket_status_code = "NoSuchBucketPolicy" elif ex.response['Error']['Code'] == "AccessDenied": bucket_status_code = "AccessDenied2Policy" else: bucket_status_code ="Can'tVerify" # cprint("Weird"+ str(ex.response['Error']), "red") # return status code return bucket_status_code