我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorama.Fore.BLACK。
def live_score(desc): mid = match_id(desc) data = c.livescore(mid) score = {} score['matchinfo'] = "{}, {}".format(data['matchinfo']['mnum'], data['matchinfo']['mchdesc']) score['status'] = "{}, {}".format(data['matchinfo']['mchstate'].title(), data['matchinfo']['status']) score['bowling'] = data['bowling'] score['batting'] = data['batting'] text = '' text += Fore.LIGHTYELLOW_EX + score['matchinfo'] + '\n' + score['status'] + '\n\n' text += Fore.BLUE + score['batting']['team'] + '\n' + Fore.BLACK for scr in reversed(score['batting']['score']): text += "{} :- {}/{} in {} overs\n".format(scr['desc'], scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['batting']['batsman']): text += "{} : {}({}) \n".format(b['name'].strip('*'), b['runs'], b['balls']) text += Fore.BLUE + "\n" + score['bowling']['team'] + '\n' + Fore.BLACK for scr in reversed(score['bowling']['score']): text += "{} :- {}/{} in {} overs\n".format(scr['desc'], scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['bowling']['bowler']): text += "{} : {}/{} \n".format(b['name'].strip('*'), b['wickets'], b['runs']) text += Fore.RESET return text
def printBoard(self): """ Print board to terminal for debugging """ def getItem(item): if item == Board.BLACK : return Fore.WHITE + "|" + Fore.BLACK + "O" elif item == Board.WHITE : return Fore.WHITE + "|" + Fore.WHITE + "O" else: return Fore.WHITE + "| " def getRow(row): return "".join(map(getItem,row)) print("\t" + Back.GREEN + " BOARD ") print("\t" + Back.GREEN + Fore.WHITE + " |0|1|2|3|4|5|6|7") for i in range(8): print("\t" + Back.GREEN + Fore.WHITE + "{}{}".format(i, getRow(self.board[i]))) sys.stdout.write(Style.RESET_ALL)
def newGame(self): """ Load board with init conditions And sync virtual board """ self.board = np.array([[0]*self.size] * self.size, dtype=int) mL = int(self.board.shape[0]/2 - 1) mR = int(self.board.shape[0]/2) self.board[mL][mL] = 1 self.board[mR][mR] = 1 self.board[mR][mL] = -1 self.board[mL][mR] = -1 self.nextTurn = self.BLACK self.syncVirtualBoard() self.gameOver = False return
def main(): colorama.init() # gratuitous use of lambda. pos = lambda y, x: '\x1b[%d;%dH' % (y, x) # draw a white border. print(Back.WHITE, end='') print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='') for y in range(MINY, 1+MAXY): print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='') print('%s%s' % (pos(MAXY, MINX), ' '*MAXX), end='') # draw some blinky lights for a while. for i in range(PASSES): print('%s%s%s%s%s' % (pos(randint(1+MINY,MAXY-1), randint(1+MINX,MAXX-1)), choice(FORES), choice(BACKS), choice(STYLES), choice(CHARS)), end='') # put cursor to top, left, and set color to white-on-black with normal brightness. print('%s%s%s%s' % (pos(MINY, MINX), Fore.WHITE, Back.BLACK, Style.NORMAL), end='')
def menu(): # Using colour from colorama: https://pypi.python.org/pypi/colorama # Formatting e.g.: Fore.COLOUR, Back.COLOUR, Style.DIM with e.g. DIM, RED, CYAN, etc.: print(Fore.BLACK + Back.WHITE + "10cbazbt3 menu:" + Style.RESET_ALL) print(Fore.YELLOW + Style.DIM + "Main:") print(" b = Blurb m = Mentions") print(" r = Reply t = Timeline") print(" blog = BLOG o = Own blurbs") print(" pins = PINS") print("Admin:") print(" Login = Login menu = show Menu") print(" Logout = Logout. sites = my Sites") print(" exit = Exit") print(Style.RESET_ALL) # DEFINE 10C POST INTERACTIONS: # LOTS OF DUPLICATION HERE! # Define the 'blurb' (social post) subroutine:
def main(self): domain_list = [] load_name = self.get_options("enterprise") print Style.BRIGHT + Fore.BLUE + "Search domain name for "+load_name + Style.RESET_ALL start_with = ["www.","http://","https://"] end_with = [".com",".fr",".org",".de",".eu"] for line in start_with: for end_line in end_with: domain = line + str(load_name) + end_line try: return_code = urllib.urlopen(domain).getcode() return_code = str(return_code) if return_code != "404": domain_list.append(domain) print Fore.GREEN + "- "+Style.RESET_ALL + domain except: Back.YELLOW + Fore.BLACK + "Can't get return code" + Style.RESET_ALL if len(domain_list) > 0: for domain in domain_list: self.export.append(domain) else: print Fore.RED + "No domain found" + Style.RESET_ALL
def browser_hacks(): print Fore.YELLOW + " ! For use module please use :use moduleName" + Style.RESET_ALL if os.path.exists("core/BHDB/"): list_module = glob.glob("core/BHDB/*.py") for module in list_module: if ".py" in module: module_name = module.split(".py")[0] module_name = module_name.replace('core/BHDB/','') if "__init__" not in module: description = "No module description found" if "#description:" in open(module).read(): description = open(module).read().split("#description:")[1] description = description.split("#")[0] print Fore.BLUE + " * "+ Style.RESET_ALL + module_name + " " + description else: print Back.RED + Fore.BLACK + "Browserhacking directory not found" + Style.RESET_ALL
def scorecard(desc): mid = match_id(desc) data = c.scorecard(mid) card = {} card['matchinfo'] = "{}, {}".format(data['matchinfo']['mnum'], data['matchinfo']['mchdesc']) card['status'] = "{}, {}".format(data['matchinfo']['mchstate'].title(), data['matchinfo']['status']) card['scorecard'] = data['scorecard'] text = '' text += Fore.LIGHTYELLOW_EX + card['matchinfo'] + '\n' + card['status'] + '\n\n' text += Fore.BLACK + '*' * 35 + '\n\n' for scr in reversed(card['scorecard']): text += Fore.LIGHTYELLOW_EX + "{} {}\n{}/{} in {} overs\n\n".format(scr['batteam'], scr['inngdesc'], scr['runs'], scr['wickets'], scr['overs']) text += Fore.BLUE + "Batting\n" text += Fore.RED + "{:<17} {:<3} {:<3} {:<3} {}\n\n".format('Name', 'R', 'B', '4', '6') for b in scr['batcard']: text += Fore.BLACK + "{:<17} {:<3} {:<3} {:<3} {}\n{}\n\n".format(b['name'], b['runs'], b['balls'], b['fours'], b['six'], b['dismissal']) text += Fore.LIGHTYELLOW_EX + "-" * 35 + "\n\n" text += Fore.BLUE + "Bowling\n" text += Fore.RED + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format('Name', 'O', 'M', 'R', 'W') for b in scr['bowlcard']: text += Fore.BLACK + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format(b['name'], b['overs'], b['maidens'], b['runs'], b['wickets']) text += Fore.BLUE + '*' * 35 + '\n\n' return text
def _enable_shell_colors(): import sys from colorama import Fore sys.ps1 = Fore.LIGHTWHITE_EX + '?? >' + Fore.RESET + ' ' sys.ps2 = Fore.BLACK + '..' + Fore.LIGHTBLACK_EX + '.' + Fore.RESET + ' '
def parseLine(line): severity = getSeverity(line) # Add color based on severity if 'severity' not in locals(): severity = 3 if severity == 0: color = Style.DIM + Fore.WHITE elif severity == 1: color = Style.NORMAL + Fore.BLUE elif severity == 2: color = Style.NORMAL + Fore.CYAN elif severity == 3: color = Style.NORMAL + Fore.WHITE elif severity == 4: color = Style.NORMAL + Fore.RED elif severity == 5: color = Style.NORMAL + Fore.BLACK + Back.RED else: color = Style.NORMAL + Fore.BLACK + Back.YELLOW # Replace html tab entity with actual tabs line = clearTags(line) line = line.replace('	', "\t") return color + line + Style.RESET_ALL
def load_tools(self): os.system('clear') action = 0 self.warning_show() export = self.export() raw_input(Back.GREEN + Fore.BLACK + "Report exported : " + os.getcwd() + "/export/" + export + ".html" + Style.RESET_ALL) while action == 0: user_input = raw_input('[DOMFf />] ') if user_input == "help": print """____________________________________________________________ | appinfo : (Load application information) | warning : (Load application Warning information) | clear : (Clear console) | exit : (Exit DOM Forensics Framework) ------------------------------------------------------------""" if user_input == "export": self.export() if user_input == "appinfo": self.app_info() if user_input == "clear": os.system('clear') if user_input == "warning": self.warning_show() if user_input == "exit": action = 1
def __init__(self): self.board = np.zeros((8,8), int) self.board[3][3] = Board.BLACK self.board[4][4] = Board.BLACK self.board[4][3] = Board.WHITE self.board[3][4] = Board.WHITE self.remaining_squares = 8*8 - 4 self.score = {Board.BLACK: 2, Board.WHITE: 2}
def getItem(item): if item == 1: return Fore.WHITE + "|" + Fore.BLACK + "O" elif item == 0: return Fore.WHITE + "| " else: return Fore.WHITE + "|" + Fore.WHITE + "O"
def isGameOver(self, t): for x in range(self.size): for y in range(self.size): valid = self.isValidMove(t, self.BLACK, x, y) or self.isValidMove(t, self.WHITE, x, y) if valid: return False return True
def updateBoard(self, t, tile, row, col): """ @param string t either 'virtual' or 'live' @param int tile either 1 or -1 1 for player 1 (black) -1 for player 2 (white) @param int row 0-7 which row @param int col 0-7 which col @return bool true if valid false if invalid move - doesn't update board """ board = self.board if t == 'live' else self.virtualBoard result = self.isValidMove(board, tile, row, col) if result != False: if t == 'live' : self.nextTurn = self.BLACK if self.nextTurn != self.BLACK else self.WHITE else: self.virtualNextTurn = self.BLACK if self.virtualNextTurn != self.BLACK else self.WHITE board[row][col] = tile for row in result: board[ row[0] ][ row[1] ] = tile if ( t == 'live'): self.syncVirtualBoard() return True else: return False
def formatException(self, ei): tb = super().formatException(ei) if iswindows: return textwrap.indent(tb, ' | ') else: return textwrap.indent(tb, Fore.BLACK + ' | ' + Fore.WHITE)
def dump_board(sx, so, move_index=None, win_indices=None, q=None): """ Dump board state to the terminal. """ for i in xrange(board_size): for j in xrange(board_size): if (i, j) == move_index: color = Fore.GREEN else: color = Fore.BLACK if not win_indices is None and (i, j) in win_indices: color += Back.LIGHTYELLOW_EX print(" ", end="") if sx[i, j] and so[i, j]: print(Fore.RED + "?" + Fore.RESET, end="") elif sx[i, j]: print(color + "X" + Style.RESET_ALL, end="") elif so[i, j]: print(color + "O" + Style.RESET_ALL, end="") else: print(".", end="") if not q is None: print(" ", end="") for j in xrange(board_size): if (i, j) == move_index: color = Fore.GREEN else: color = Fore.BLACK if not (sx[i, j] or so[i, j]) or (i, j) == move_index: print(color + " %6.3f" % q[i, j] + Style.RESET_ALL, end="") else: print(Fore.LIGHTBLACK_EX + " * " + Style.RESET_ALL, end="") print() print()
def authorise(): # Define 'headertokenonly' and 'headers' as global variables, with actual values defined below: global headertokenonly global headers # Define 'headertokenonly' global authentication variable - read from /home/pi/10cv4/authtoken.txt, # ***The text file MUST exist and contain one line, ONLY the text of the auth token,*** # It's returned from the API at the end of the 'Login' subroutine, # This header contains only the token - used when only an auth header is required, # First check if it exists, # If it does not, ask the user to login for the first time: try: open("authtoken.txt") except IOError as e: os.system('clear') print("") print(Fore.BLACK + Back.WHITE + "10cbazbt3:") print("") print(Fore.BLACK + Back.RED + "Please Login for the first time." + Style.RESET_ALL) print("") login() tempinput = input(Fore.YELLOW + "Please press [enter] to continue" + Style.RESET_ALL) # Then carry on creating the authorisation headers: authtokenonlyfile = open("authtoken.txt", "r") authtokenonly = authtokenonlyfile.read() headertokenonly = {'Authorization': authtokenonly} # Define the 'headers' global variable using 'authtokenonly' from above, # This header is used throughout the application: headers = {'Authorization': authtokenonly, 'Content-Type': 'application/x-www-form-urlencoded'} # Define the 'login' subroutine: # Getting and applying the auth token is unnecessarily long, # Requires less of the file i/o:
def login(): # Input account name: my_acctname = input(Fore.YELLOW + Style.DIM + "10C Username (account email address): " + Fore.WHITE) # Input account password: my_acctpass = getpass.getpass(Fore.YELLOW + Style.DIM + "10C Password (is not shown onscreen): " + Style.RESET_ALL) # Construct the login URL & data passed to the API: url = 'https://api.10centuries.org/auth/login' loginheaders = {'Content-Type': 'application/x-www-form-urlencoded'} data = {'client_guid': my_client_guid, 'acctname': my_acctname, 'acctpass': my_acctpass} response = requests.post(url, headers=loginheaders, data=data) # Saves the server's JSON response to 'loginresponse.txt': file = open("loginresponse.txt", "w") file.write(response.text) file.close() # Extracts the auth token from the JSON file: json_data = open("loginresponse.txt", "r") decoded = json.load(json_data) temptoken = decoded['data']['token'] # Saves just the auth token to authtoken.txt: file = open("authtoken.txt", "w") file.write(temptoken) file.close() # Let the user know the application is authorised: print("") print(Fore.BLACK + Back.GREEN + "Authorised" + Style.RESET_ALL + Fore.YELLOW + Style.DIM + " (but check for a 'Connected' indicator!)" + Style.RESET_ALL) print("") setloginstatus("In") authorise() # Define the 'logout' subroutine:
def checkloginstatusfile(): try: open("loginstatus.txt") except IOError as e: print(Fore.BLACK + Back.RED + "Please Login." + Style.RESET_ALL) setloginstatus("Out") #Define 'checkloginstatus' subroutine:
def checkloginstatus(): checkloginstatusfile() loginstatusfile = open("loginstatus.txt", "r") loginstatus = loginstatusfile.read() if loginstatus == "Out": print(Fore.BLACK + Back.RED + "Please Login." + Style.RESET_ALL) elif loginstatus == "In": print(Fore.GREEN + "Connected." + Style.RESET_ALL) # Define the 'showapiresponse' subroutine: # Displays API response to POST routines:
def run_module(self): ret = self.check_require() if ret == False: print Back.YELLOW + Fore.BLACK + "Please set the required parameters" + Style.RESET_ALL else: self.main()
def export_data(export, export_file, export_status, title, argv): if len(export) > 0: if export_file == "": if argv == False: user_input = raw_input("operative (export file name ?) > ") else: user_input = argv if os.path.exists("export/"+user_input): export_file = "export/"+user_input elif os.path.exists(user_input): export_file = user_input else: print Fore.GREEN + "Writing " + user_input + " file" + Style.RESET_ALL export_file = "export/"+user_input export_data(export, export_file, export_status, title, argv) elif export_status == False: file_open = open(export_file,"a+") file_open.write(title) for line in export: aux = type(line) if str(aux) == "<type 'dict'>": for item in line.items(): file_open.write("- " + item[0] + ": " + item[1], ) file_open.write("\n") else: file_open.write("- " + line +"\n") print Fore.GREEN + "File writed : " + export_file + Style.RESET_ALL file_open.close() export_status = True else: print Back.YELLOW + Fore.BLACK + "Module empty result" + Style.RESET_ALL
def main(self): manufactor = str(self.get_options("manufactor")) search_link = "http://www.defaultpassword.com/?action=dpl&char="+manufactor print Fore.GREEN + "Searching for passwords" + Style.RESET_ALL req = requests.get(search_link) html = req.content result = html.split('<TR VALIGN="top">') try: result.pop(0) result.pop(0) print ('{}{} ! {:^17}| {:^20}| {:^10}| {:^15}| {:^15}{}' \ .format(Back.BLACK, Fore.YELLOW, 'Manufactor', 'Product', 'Protocol', 'User', 'Password', Style.RESET_ALL)) for line in result: spliting = line.split('<TD NOWRAP>') string = '' for element in spliting: if "</TD>" in element and element.strip() != '': manufactor = spliting[1].split('</TD>')[0] product = spliting[2].split('</TD>')[0] protocol = spliting[4].split('</TD>')[0] user = spliting[5].split('</TD>')[0] password = spliting[6].split('</TD>')[0] string_export = {'manufactor':manufactor,'product':product,'protocol':protocol,'user':user,'password':password} self.export.append(string_export) print('{} * {}{:17}{}|{} {:^20}{}|{} {:^10}{}|{} {:^15}{}|{} {:^15}' \ .format(Fore.BLUE, Style.RESET_ALL, manufactor, \ Fore.YELLOW, Style.RESET_ALL, product, \ Fore.YELLOW, Style.RESET_ALL, protocol, \ Fore.YELLOW, Style.RESET_ALL, user, Fore.YELLOW, Style.RESET_ALL, password)) except IndexError: print Fore.RED + "No results were found for this manufacturer." + Style.RESET_ALL
def show_module(): if os.path.exists("core/modules/"): list_module = glob.glob("core/modules/*.py") for module in list_module: if ".py" in module: module_name = module.split(".py")[0] module_name = module_name.replace('core/modules/','') if "__init__" not in module: description = "No module description found" if "#description:" in open(module).read(): description = open(module).read().split("#description:")[1] description = description.split("#")[0] print Fore.BLUE + " * "+ Style.RESET_ALL + module_name + " " + description else: print Back.RED + Fore.BLACK + "Modules directory not found"+ Style.RESET_ALL
def create_initialization_info(directory_name): print(GET_STARTED_INFO.format( fore_black=Fore.BLACK, back_green=Back.GREEN, fore_white=Fore.WHITE, fore_reset=Fore.RESET, back_reset=Back.RESET, style_bright=Style.BRIGHT, style_normal=Style.NORMAL, fore_green=Fore.GREEN, dir_name=directory_name ))
def black(self, s): return Fore.BLACK # ??:? ?:?