Python colorama.Fore 模块,WHITE 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorama.Fore.WHITE

项目:routerPWN    作者:lilloX    | 项目源码 | 文件源码
def ex_print (type, msg, ret):
    colorama.init()
    # Define color and style constants
    c_error = Fore.RED
    c_action = Fore.YELLOW
    c_ok = Fore.GREEN
    c_white = Fore.WHITE
    s_br = Style.BRIGHT
    s_reset = Style.RESET_ALL
    message = {
        "error": c_error + s_br,
        "action": c_action,
        "positive": c_ok + s_br,
        "info": c_white + s_br,
        "reset": s_reset
    }
    style = message.get(type, s_reset)
    if ret == 0:
        print(style + msg, end = "")
    else:
        print(style + msg)
项目:pyability    作者:syedur-rahman    | 项目源码 | 文件源码
def display_warning_to_user(self):
        """ display warning to user
        show user the commands + switches and ask if they
        would still like to proceed or not """

        user_message = Fore.CYAN + "\nYou are about to run the following commands:"
        print(user_message)

        for command in self.commands:
            print(command)

        user_message = Fore.CYAN + "\nOn the following devices:"
        print(user_message)

        for device in sorted(self.devices.keys()):
            print(device)

        user_message = Fore.RED + "\nAre you sure you wish to proceed? (y/n) " + Fore.WHITE
        user_input = input(user_message)

        if user_input.lower() == 'y':
            return True
        else:
            return False
项目:8080py    作者:sadboyzvone    | 项目源码 | 文件源码
def banner():
    print(Style.DIM)
    print('     ___________________________')
    print('    /                           /\\')
    print('   /     sadboyzvone\'s        _/ /\\')
    print('  /        Intel 8080        / \/')
    print(' /         Assembler         /\\')
    print('/___________________________/ /')
    print('\___________________________\/')
    print(' \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\'
          + Style.RESET_ALL + Style.BRIGHT)
    print(Fore.WHITE + '\nPowered by ' + Fore.BLUE + 'Pyt'
          + Fore.YELLOW + 'hon' + Fore.WHITE
          + '\nCopyright (C) 2017, Zvonimir Rudinski')

# Print usage information
项目:MailFail    作者:m0rtem    | 项目源码 | 文件源码
def load_url(url, timeout):
    # Build URL query to email signup page
    urlquery = "http://" + url + "/m-users-a-email_list-job-add-email-" + targetEmail + "-source-2.htm"
    print_out(Style.BRIGHT + Fore.WHITE + "Sending request to: " + url)
    # Build the request
    req = urllib.request.Request(
        urlquery, 
        data=None, 
        headers={
            'User-Agent': random.choice(useragents),
            'Host': url
        }
    )
    # Send
    try:
        f = urllib.request.urlopen(req)
        print_out(Style.BRIGHT + Fore.GREEN + "Successfully sent!")
        f.close()
    except urllib.error.URLError as e:
        print_out(Style.BRIGHT + Fore.RED + e.reason)
项目:othello-rl    作者:jpypi    | 项目源码 | 文件源码
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)
项目:othello-rl    作者:jpypi    | 项目源码 | 文件源码
def printBoard(self, t='live'):
        """
        Print board to terminal for debugging
        @param string type 'virtual' or 'live'
        """
        board = self.board if t == 'live' else self.virtualBoard

        print(Back.GREEN +              "\t      BOARD      ")

        # Print column titles
        head = Back.GREEN + Fore.WHITE + "\t "
        for i in range(self.board.shape[0]):
            head += '|' + str(i)
        print(head)

        # Print rows
        for i in range(self.board.shape[0]):
            print(Back.GREEN + Fore.WHITE + "\t" + str(i) + getRow(board[i]))
        print(Style.RESET_ALL)

        return
项目:requests-arcgis-auth    作者:DOI-BLM    | 项目源码 | 文件源码
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='')
项目:python-ids-alarm    作者:kellerza    | 项目源码 | 文件源码
def getparam(ser, p_name, p_data):
    """Decode a specific parameter from the serial port."""
    printc(Back.RED + p_name, prepend='\n')
    for typ in p_data:
        schr = ser.read()
        if typ == 'h':
            printc(c2hex(schr), Fore.GREEN)
        elif typ == 'H':
            if len(HIGHLIGHT):
                HIGHLIGHT.popleft()
            HIGHLIGHT.append(c2hex(schr))
            printc(c2hex(schr), Fore.BLUE)
        elif typ == 'a':
            printc(c2ascii(schr) or c2hex(schr), Fore.WHITE, prepend='')
        else:
            printc(c2hex(schr), Fore.WHITE)
    printc(Style.RESET_ALL, prepend='')
项目:10cbazbt3    作者:bazbt3    | 项目源码 | 文件源码
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:
项目:operative-framework    作者:graniet    | 项目源码 | 文件源码
def show_options(require):
    #print Back.WHITE + Fore.WHITE + "Module parameters" + Style.RESET_ALL
    for line in require:
        if require[line][0]["value"] == "":
        value = "No value"
    else:
        value = require[line][0]["value"]
    if require[line][0]["required"] == "yes":
        if require[line][0]["value"] != "":
            print Fore.GREEN+Style.BRIGHT+ "+ " +Style.RESET_ALL+line+ ": " +value
        else:
            print Fore.RED+Style.BRIGHT+ "- " +Style.RESET_ALL+line+ "(" +Fore.RED+ "is_required" +Style.RESET_ALL+ "):" +value
    else:
        if require[line][0]["value"] != "":
        print Fore.GREEN+Style.BRIGHT+ "+ " +Style.RESET_ALL+line + ": " +value
        else:
        print Fore.WHITE+Style.BRIGHT+ "* " +Style.RESET_ALL+line + "(" +Fore.GREEN+ "optional" +Style.RESET_ALL+ "):" +value
    #print Back.WHITE + Fore.WHITE + "End parameters" + Style.RESET_ALL
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def print_and_log(to_print, level='info', logger=None, display=True):
    if display:
        if level == 'default':
            for line in to_print:
                print Fore.WHITE + line + '\r'
        if level == 'info':
            print_info(to_print)
        elif level == 'error':
            print_error(to_print)

    if logger is not None:
        write_to_logger(logger, to_print, level)

    sys.stdout.flush()
项目:8080py    作者:sadboyzvone    | 项目源码 | 文件源码
def printHelp():
    print('\nThis ' + Fore.BLUE + 'Intel' + Fore.WHITE
          + ' 8080 assembler was made for ' + Fore.BLUE + 'Project '
          + Fore.YELLOW + 'Week' + Fore.WHITE + ' at my school.')
    print('It is written in ' + Fore.BLUE + 'Pyt' + Fore.YELLOW + 'hon'
          + Fore.WHITE)
    print('Modules: ' + Fore.RED + 'Co' + Fore.BLUE + 'lo'
          + Fore.YELLOW + 'ra' + Fore.GREEN + 'ma' + Fore.WHITE)
    print('\nPass a file path as an arguement.')


# Main function
项目:binarly-query    作者:binarlyhq    | 项目源码 | 文件源码
def color_row(row):
    color = Fore.WHITE
    label = "."
    if u'label' in row:
        color = LABEL_COLOR.get(row[u'label'], Fore.WHITE)
        label = row[u'label']
        row[u'label'] = "%s%s%s" % (color, label, Style.RESET_ALL)

    row['family'] = "%s%s%s" % (color, row.get('family', "."), Style.RESET_ALL)
    row['size'] = smart_size(row.get(u'size', "."))
    return row
项目:BrundleFuzz    作者:carlosgprado    | 项目源码 | 文件源码
def m_fatal(self, m):
        m = '[X] ' + m
        if COLORAMA:
            print Fore.WHITE + Back.RED + m
        else:
            print m
项目:BrundleFuzz    作者:carlosgprado    | 项目源码 | 文件源码
def m_fatal(self, m):
        m = '[X] ' + m
        if COLORAMA:
            print Fore.WHITE + Back.RED + m
        else:
            print m
项目:BrundleFuzz    作者:carlosgprado    | 项目源码 | 文件源码
def m_fatal(self, m):
        m = '[X] ' + m
        if COLORAMA:
            print Fore.WHITE + Back.RED + m
        else:
            print m
项目:python-ossi    作者:iskhomutov    | 项目源码 | 文件源码
def print_major_alarms(mj):
    """
    Args:
        mj (int): Counts of major alarms

    Returns:
        str: Colorized information by using colorama
    """
    if mj > 0:
        return Back.RED + Fore.WHITE + str(mj) + Fore.RESET + Back.RESET
    else:
        return Fore.GREEN + str(mj) + Fore.RESET
项目:demos    作者:dfirence    | 项目源码 | 文件源码
def run_plugin( plugin ):
    start = time.time()
    print '[-] Start {}'.format( plugin[1] )
    with open( devnull, 'w' ) as FNULL:
        subprocess.call( plugin, stdout=FNULL )

    #end = '[+] Ends   {0:<20}: {:.2f}s'.format( plugin[1], time.time() - start )
    end = '{:.2f}s'.format( time.time() - start )
    print (Fore.WHITE + '[+]') , 'Ends  {:25}--> {}'.format( plugin[1], end )
    return
项目:clisaurus    作者:steffenkarlsson    | 项目源码 | 文件源码
def present_synonyms(synonym_groups, query):
    table = defaultdict(list)
    for sg in sorted(synonym_groups.keys()):
        synonyms = synonym_groups[sg]
        table[sg] = [COLORS[category - 1] + word
                     for category in sorted(synonyms.keys(), reverse=True)
                     for word in sorted(synonyms[category])]
        table[sg].append(Fore.WHITE + "")

    print ">> Results from searching: %s, where the first row denotes the context of where the synonyms are used.\n" % query
    print tabulate(table, tablefmt="rst", headers="keys")
项目:almar    作者:scriptotek    | 项目源码 | 文件源码
def __str__(self):
        ign = ' (ignoring any extra subfields)' if self.ignore_extra_subfields else ''

        args = (Fore.WHITE + six.text_type(self.source) + Style.RESET_ALL,
                Fore.WHITE + six.text_type(self.target) + Style.RESET_ALL,
                ign)
        return 'Replace `{}` ? `{}`{}'.format(*args)
项目:almar    作者:scriptotek    | 项目源码 | 文件源码
def _run(self, marc_record):
        print()
        time.sleep(1)
        print('{}{}: {}{}'.format(Fore.WHITE, marc_record.id, marc_record.title(), Style.RESET_ALL).encode('utf-8'))
        for field in marc_record.fields:
            if field.tag.startswith('6'):
                if field.sf('2') == self.source.sf['2']:
                    if field.match(self.source):
                        print('  > {}{}{}'.format(Fore.YELLOW, field, Style.RESET_ALL).encode('utf-8'))
                    else:
                        print('    {}{}{}'.format(Fore.YELLOW, field, Style.RESET_ALL).encode('utf-8'))
                else:
                    print('    {}'.format(field).encode('utf-8'))

        while True:
            targets = pick('Make a selection (or press Ctrl-C to abort)', self.targets, OrderedDict((
                ('REMOVE', 'None of them (remove the field)'),
            )))
            if 'REMOVE' in targets and len(targets) > 1:
                log.warning('Invalid selection. Please try again or press Ctrl-C to abort.')
            else:
                break

        if len(targets) == 0:
            log.info('Skipping this record')
            return 0

        tasks = []
        if 'REMOVE' in targets:
            tasks.append(DeleteTask(self.source, ignore_extra_subfields=self.ignore_extra_subfields))
        else:
            tasks.append(ReplaceTask(self.source, targets[0], ignore_extra_subfields=self.ignore_extra_subfields))
            for target in targets[1:]:
                tasks.append(AddTask(target))

        modified = 0
        for task in tasks:
            modified += task.run(marc_record)

        return modified
项目:almar    作者:scriptotek    | 项目源码 | 文件源码
def __str__(self):
        return 'List titles having `{}`'.format(Fore.WHITE + six.text_type(self.source) + Style.RESET_ALL)
项目:almar    作者:scriptotek    | 项目源码 | 文件源码
def __str__(self):
        return 'Delete `{}`'.format(Fore.WHITE + six.text_type(self.source) + Style.RESET_ALL)
项目:almar    作者:scriptotek    | 项目源码 | 文件源码
def __str__(self):
        return 'Add `{}`'.format(Fore.WHITE + six.text_type(self.target) + Style.RESET_ALL)
项目:cryptomon    作者:Mim0oo    | 项目源码 | 文件源码
def color_green(text):
    return Fore.GREEN+text+Fore.WHITE


# JSON validator function
项目:torrent-dl    作者:animeshkundu    | 项目源码 | 文件源码
def screen_data(self, defrag=False):
        status = self.status
        text = Fore.WHITE
        text += term.bold('Pyflix\n\n')
        text += STATES[status.state]
        text += term.yellow(' %.2f%% complete ' % (status.progress * 100))
        rates = self.rates()
        rate_text = '(down: %.1f kB/s up: %.1f kB/s peers: %d)\n' % \
                    (rates[0], rates[1], status.num_peers)
        text += term.green(rate_text)

        if defrag:
            text += self.defrag()
            text += Fore.WHITE
            text += "\n\n"

        if self._video_file is not None:
            text += term.white("Serving ")
            text += term.yellow(self.video_file[0])
            text += term.white(" on ")
            text += term.blue("http://localhost:%s\n") % self.port

        text += term.white("Elapsed Time: ")
        text += term.red(self.elapsed_time())
        text += "\n"
        return text
项目:vanilla-nodebb-importer    作者:Linux-statt-Windows    | 项目源码 | 文件源码
def log(text):
    print(Fore.GREEN + '==> ' + Fore.WHITE + text)
项目:vanilla-nodebb-importer    作者:Linux-statt-Windows    | 项目源码 | 文件源码
def log_warn(text):
    print(Fore.YELLOW + '==> Warning: ' + Fore.WHITE + text)
项目:vanilla-nodebb-importer    作者:Linux-statt-Windows    | 项目源码 | 文件源码
def log_err(text):
    print(Fore.RED + '==> Error: ' + Fore.WHITE + text)


# NOTE: If you use this script as module, call this function!
项目:TorStat    作者:rootlabs    | 项目源码 | 文件源码
def TOR_CHECK_PRNT(data):
    if (data["IsTor"]==True):
        print ("[" + Fore.GREEN + Style.BRIGHT + "+" + Style.RESET_ALL + "]" + Fore.GREEN + Style.BRIGHT + " TorStat's network traffic was routed through tor, onto the next stage...\n" + Style.RESET_ALL)
        return True
    elif (data["IsTor"]==False):
        print ("[" + Fore.YELLOW + Style.BRIGHT + "!" + Style.RESET_ALL + "]" + Fore.YELLOW + Style.BRIGHT +" TorStat cannot perform any more recon on the tor servers because TorStat's network traffic was not routed through tor.\n\t " + Style.RESET_ALL + Fore.WHITE + Style.DIM + "=> try : proxychains python TorStat.py\n" + Style.RESET_ALL)
        return False
项目:TorStat    作者:rootlabs    | 项目源码 | 文件源码
def NODE_INFO(IP_ADDR):
    resp = urllib2.urlopen("https://onionoo.torproject.org/details?search=%s"%(IP_ADDR))
    json_data = resp.read()
    data = json.loads(json_data, object_pairs_hook=OrderedDict)
    rp = bp = None
    colors_lst = [Fore.GREEN + Style.BRIGHT, Fore.RED + Style.BRIGHT, Fore.YELLOW + Style.BRIGHT, Fore.WHITE + Style.BRIGHT, Fore.CYAN + Style.BRIGHT]
    for key, value in data.items():
            if key == "version" or key == "bridges":
                continue
            if key == "relays_published":
                rp = value
            if key == "bridges_published":
                bp = value
            if key == "relays":
                for each in value:
                    for e_key, e_val in each.items():
                        #if lists
                        if e_key == "or_addresses":
                            print (Fore.GREEN + Style.BRIGHT + e_key.upper() + Fore.WHITE + Style.BRIGHT + " : " + ','.join(e_val))
                            continue
                        if e_key.lower() == "exit_policy_summary" or e_key.lower() == "exit_policy" or e_key.lower() == "exit_policy_v6_summary": 
                            continue
                        if str(e_val).startswith("[") and str(e_val).endswith(']'):
                            print (Fore.GREEN + Style.BRIGHT + e_key.upper() + Style.RESET_ALL)
                            for ef in e_val:
                                print Fore.BLUE + Style.BRIGHT + "\t=> "+ ef + Style.RESET_ALL
                            continue
                        try:    
                            print (Fore.GREEN + Style.BRIGHT + e_key.upper().replace('_',' ') + Style.RESET_ALL + " : " + \
                        Fore.WHITE + Style.BRIGHT + str(e_val))     
                        except: pass
                    print
            if (rp!=None and bp!= None):
                print (Fore.GREEN + Style.BRIGHT + "RELAYS PUBLISHED" + Style.RESET_ALL + " : " + Fore.WHITE + Style.BRIGHT + rp)
                print (Fore.GREEN + Style.BRIGHT + "BRIDGES PUBLISHED" + Style.RESET_ALL + " : " + Fore.WHITE + Style.BRIGHT + bp)
项目:screeps_console    作者:screepers    | 项目源码 | 文件源码
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('&#09;', "\t")
    return color + line + Style.RESET_ALL
项目:petal    作者:hdmifish    | 项目源码 | 文件源码
def log(self, message):
        print(Fore.WHITE + "[LOG] " + self.timestamp() + " " +
              message.encode('ascii', 'ignore').decode('ascii') + Fore.RESET)
        return
项目:othello-rl    作者:jpypi    | 项目源码 | 文件源码
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}
项目:othello-rl    作者:jpypi    | 项目源码 | 文件源码
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"
项目:othello-rl    作者:jpypi    | 项目源码 | 文件源码
def validateBoard(self, t='live'):
        '''
        Determines if players can still make moves.
        If a player cannot move, their turn is automatically skipped.
        If neither player can move, the game has ended.
        Returns False if the game continues, -1 or 1 if the game has ended.
        '''
        if self.isGameOver(t):
            print("Game Over")
            wOwn = self.getOwnership(self.WHITE)
            bOwn = self.getOwnership(self.BLACK)
            if wOwn > bOwn:
                print("White wins with", wOwn, "territory to black's", bOwn, ".")
                return self.WHITE
            else:
                print("Black wins with", bOwn, "territory to white's", wOwn, ".")
                return self.BLACK

        nt = self.nextTurn if t == 'live' else self.virtualNextTurn
        if not self.canMove(t, nt):
            if nt == self.BLACK:
                print("Black cannot move, turn passed.")
                if t == 'live':
                    self.nextTurn = self.WHITE
                else:
                    self.virtualNextTurn = self.WHITE
            else:
                print("White cannot move, turn passed.")
                if t == 'live':
                    self.nextTurn = self.BLACK
                else:
                    self.virtualNextTurn = self.BLACK
        return False
项目:othello-rl    作者:jpypi    | 项目源码 | 文件源码
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
项目:githass    作者:fronzbot    | 项目源码 | 文件源码
def __init__(self):
        from colorama import init, Fore, Style

        init(autoreset=True)
        self.colors = {'red': Fore.RED,
                       'yellow': Fore.YELLOW,
                       'green': Fore.GREEN,
                       'white': Fore.WHITE,
                       'cyan': Fore.CYAN,
                       'reset': Style.RESET_ALL
                      }
项目:Pokemon-Vortex-3-Ultimate-Bot    作者:Kyzaghan    | 项目源码 | 文件源码
def writelog(self, message, log_type="info", do_print=True):
        """
        Write log file
        :param message: Log Text
        :param log_type: Log type (info, critical, error, warning, success, catch)
        :param do_print: Print to screen
        """
        try:
            print(Style.RESET_ALL)
            message = "[" + time.strftime("%d-%m-%Y %H:%M %S") + "]" + message
            if log_type == "critical":
                self.l.critical(message)
                if do_print:
                    print(Fore.RED + Style.BRIGHT + message)
            elif log_type == "warning":
                self.l.warning(message)
                if do_print:
                    print(Fore.YELLOW + message)
            elif log_type == "error":
                self.l.error(message)
                if do_print:
                    print(Fore.RED + message)
            elif log_type == "info":
                self.l.info(message)
                if do_print:
                    print(Fore.WHITE + message)
            elif log_type == "success":
                self.l.info(message)
                if do_print:
                    print(Fore.GREEN + message)
            elif log_type == "catch":
                self.l.info(message)
                if do_print:
                    print(Fore.BLUE + message)
        except Exception as e:
            print(str(e))
项目:bonobo    作者:python-bonobo    | 项目源码 | 文件源码
def formatException(self, ei):
        tb = super().formatException(ei)
        if iswindows:
            return textwrap.indent(tb, ' | ')
        else:
            return textwrap.indent(tb, Fore.BLACK + ' | ' + Fore.WHITE)
项目:EmiyaEngine    作者:Sg4Dylan    | 项目源码 | 文件源码
def FinSaveFile(self):
        init(autoreset=True)
        OutputFilePath = os.path.abspath(
            os.path.join(self.ReadyFilePath, os.pardir)) + "\\"
        OutputFileName = OutputFilePath + 'Output_%s.wav' % uuid.uuid4().hex
        librosa.output.write_wav(
            OutputFileName, self.AfterSignal, self.AfterSignalSR)
        print(Back.GREEN + Fore.WHITE + "SAVE DONE" +
              Back.BLACK + " Output path -> " + OutputFileName)
        logger.info(Back.GREEN + Fore.WHITE + "SAVE DONE" +
                     Back.BLACK + " Output path -> " + OutputFileName)
项目:EmiyaEngine    作者:Sg4Dylan    | 项目源码 | 文件源码
def FinSaveFile(self):
        init(autoreset=True)
        SaveFilePath = self.OutputFilePath
        if self.OutputFilePath == '':
            SaveFilePath = os.path.abspath(os.path.join(self.ReadyFilePath, os.pardir)) + "\\"
            OutputFileName = SaveFilePath + 'Output_%s.wav' % uuid.uuid4().hex
        librosa.output.write_wav(SaveFilePath, self.AfterSignal, self.AfterSignalSR)
        print(Back.GREEN + Fore.WHITE + "SAVE DONE" + Back.BLACK + " Output path -> " + SaveFilePath)
        logger.info("SAVE DONE  Output path -> " + SaveFilePath)
项目:python-ids-alarm    作者:kellerza    | 项目源码 | 文件源码
def main():
    init()
    ser = serial.Serial(COM, 19200)
    while True:
        schr = ser.read()
        char = c2ascii(schr)
        chx = c2hex(schr)
        if char == 'D':
            getparam(ser, 'D', 'Haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah')
            getparam(ser, '_', 'hhhhahhhhhHhhhhh')
        elif char == 'S':
            getparam(ser, 'S', 'Hhhhh')
            getparam(ser, '_', 'hhhhahhhhhHhhhhh')
        elif char == 'R':
            getparam(ser, 'R', 'hhhhh')
        elif char == 'C':
            getparam(ser, 'C', 'hhhhhhhhhh')
        elif char == 'B':
            getparam(ser, 'B', 'hhh')
        #elif char == 'Z':
        #    getparam(ser, 'Z', 'h')
        #elif char == 'W':
        #    getparam(ser, 'W', 'H')
        elif char and ('A' <= char and char <= 'Z' or
                     'a' <= char and char <= 'z'):
            printc(char, Fore.WHITE, prepend = '  ')
        else:
            printc(chx, Fore.YELLOW)
项目:alma-slipsomat    作者:scriptotek    | 项目源码 | 文件源码
def _can_continue(self, local_txt, remote_txt, msg):
        # Compare text checksum with value in status.json

        if self.checksum is None:
            return True  # it's a new letter

        if remote_txt is not None and normalize_line_endings(remote_txt) == normalize_line_endings(local_txt):
            self.console_msg(Fore.GREEN + 'no changes' + Style.RESET_ALL)
            return False

        remote_txt = normalize_line_endings(remote_txt)
        remote_chks = [
            get_sha1(remote_txt),
            get_sha1(remote_txt + "\n"),
        ]

        if self.checksum in remote_chks:
            return True

        print()
        print('\n' + Back.RED + Fore.WHITE + '\n\n  Warning: ' + msg % {'local_sha': self.checksum[:8], 'remote_sha': get_sha1(remote_txt)[:8]} + '\n' + Style.RESET_ALL)
        msg = 'Continue with {}?'.format(self.filename)
        if remote_txt is None:
            return input("%s [y: yes, n: no] " % msg).lower()[:1] == 'y'
        else:
            while True:
                response = input(Fore.CYAN + "%s [y: yes, n: no, d: diff] " % msg + Style.RESET_ALL).lower()[:1]
                if response == 'd':
                    show_diff(remote_txt, local_txt)
                else:
                    return response == 'y'
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def _wrap_color(code_string):
    """Wrap key parts in styling and resets.
    Stying for each key part from, 
    (col_offset, fromlineno) to (end_col_offset, end_lineno).
    Note: use this to set color back to default (on mac, and others?): 
          Style.RESET_ALL + Style.DIM
    """
    ret = Style.BRIGHT + Fore.WHITE + Back.BLACK
    ret += code_string
    ret += Style.RESET_ALL + Style.DIM + Fore.RESET + Back.RESET
    return ret
项目:10cbazbt3    作者:bazbt3    | 项目源码 | 文件源码
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:
项目:10cbazbt3    作者:bazbt3    | 项目源码 | 文件源码
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:
项目:Shiro    作者:ffao    | 项目源码 | 文件源码
def cprint(s, log_level):
        colors = {
            'debug': (Fore.WHITE, Style.NORMAL),
            'info': (Fore.CYAN, Style.NORMAL),
            'warning': (Fore.YELLOW, Style.BRIGHT),
            'error': (Fore.RED, Style.BRIGHT),
            'default': (Fore.WHITE, Style.NORMAL)
        }
        color = (colors[log_level] if log_level in colors else colors['default'])
        print(color[0], end='')
        print(color[1], end='')
        print(s)
        print(Style.RESET_ALL)
项目:fish-hook    作者:dcalsky    | 项目源码 | 文件源码
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
    ))
项目:PacPaw    作者:Sreyas-Sreelal    | 项目源码 | 文件源码
def print_white( str ):
    print( Style.BRIGHT + Fore.WHITE + str );