Python源码示例:colorama.Style.DIM

示例1
def print_results(self,results):
    try:
      if results['status'] == 'Pass':
        print ("Status: " + Fore.GREEN + 'Pass' + Fore.RESET)
      elif results['status'] == 'Fail':
        print ("Status: " + Fore.RED + 'Fail' + Fore.RESET)
    except KeyError:
      pass
    except TypeError:
      pass
    print "Description: " + results['descr']
    try:
      res = str(results['output'])
      print "Output: "
      print(Style.DIM + res + Style.RESET_ALL)
    except KeyError:
      pass
    print "\n" 
示例2
def callable_virtualenv():
    """
    Example function that will be performed in a virtual environment.

    Importing at the module level ensures that it will not attempt to import the
    library before it is installed.
    """
    from colorama import Fore, Back, Style
    from time import sleep
    print(Fore.RED + 'some red text')
    print(Back.GREEN + 'and with a green background')
    print(Style.DIM + 'and in dim text')
    print(Style.RESET_ALL)
    for _ in range(10):
        print(Style.DIM + 'Please wait...', flush=True)
        sleep(10)
    print('Finished') 
示例3
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 
示例4
def new_version_news(latest):
    print('', Icons.PARTY + Style.BRIGHT + Fore.CYAN,
          'VERSION', Fore.RED + latest + Fore.CYAN,
          'IS NOW AVAILABLE!', Fore.RESET)

    print('', Icons.RIGHT_ARROW, Style.DIM + 'Upgrade:',
          Fore.YELLOW + 'pip install -U lightnovel-crawler', Style.RESET_ALL)

    if Icons.isWindows:
        print('', Icons.RIGHT_ARROW, Style.DIM + 'Download:',
              Fore.YELLOW + 'https://rebrand.ly/lncrawl', Style.RESET_ALL)
    elif Icons.isLinux:
        print('', Icons.RIGHT_ARROW, Style.DIM + 'Download:',
              Fore.YELLOW + 'https://rebrand.ly/lncrawl-linux', Style.RESET_ALL)
    # end if

    print('-' * LINE_SIZE)
# end def 
示例5
def color(s, c, style="bright"):
    color_map = {
        "black": Fore.BLACK,
        "red": Fore.RED,
        "green": Fore.GREEN,
        "yellow": Fore.YELLOW,
        "blue": Fore.BLUE,
        "magenta": Fore.MAGENTA,
        "cyan": Fore.CYAN,
        "white": Fore.WHITE,
    }
    style_map = {
        "dim": Style.DIM,
        "normal": Style.NORMAL,
        "bright": Style.BRIGHT,
    }

    return color_map[c] + style_map[style] + s + Style.RESET_ALL 
示例6
def default_prefix_template(self, record):
        """Return the prefix for the log message. Template for Formatter.

        :param: record: :py:class:`logging.LogRecord` object. this is passed in
        from inside the :py:meth:`logging.Formatter.format` record.

        """
        reset = [Style.RESET_ALL]
        levelname = [
            LEVEL_COLORS.get(record.levelname), Style.BRIGHT,
            '%(levelname)-10s',
            Style.RESET_ALL, ' '
        ]
        asctime = [
            '', Fore.BLACK, Style.DIM, Style.BRIGHT,
            '%(asctime)-10s',
            Fore.RESET, Style.RESET_ALL, ' '
        ]

        return "".join(reset + asctime + levelname + reset) 
示例7
def colorize_direction(direction):
    """
    Green for the up direction,
    gray for the same, and red for the down direction
    """
    if direction == 1:
        return Fore.GREEN + '↑' + Style.RESET_ALL
    if direction == -1:
        return Fore.RED + '↓' + Style.RESET_ALL
    return Style.DIM + '=' + Style.RESET_ALL 
示例8
def _colorize_frame(s_frame):
    """
    Colorize frame in string s_frame
    """

    output = []
    for line in s_frame.splitlines():
        line = line.decode('utf-8')\
                .replace(u'lqqqq', Style.DIM + u'lqqqq')\
                .replace(u'tqqqq', Style.DIM + u'tqqqq')\
                .replace(u'mqqqq', Style.DIM + u'mqqqq')\
                .replace(u'x', Style.DIM + u'x' + Style.RESET_ALL)\
                .replace(u'qqqqk', u'qqqqk' + Style.RESET_ALL)\
                .replace(u'qqqqu', u'qqqqu' + Style.RESET_ALL)\
                .replace(u'qqqqj', u'qqqqj' + Style.RESET_ALL)\
                .encode('utf-8')

        line = line.decode('utf-8')\
                .replace(u'┌────', Style.DIM + u'┌────')\
                .replace(u'├────', Style.DIM + u'├────')\
                .replace(u'└────', Style.DIM + u'└────')\
                .replace(u'│', Style.DIM + u'│' + Style.RESET_ALL)\
                .replace(u'────┐', u'────┐' + Style.RESET_ALL)\
                .replace(u'────┤', u'────┤' + Style.RESET_ALL)\
                .replace(u'────┘', u'────┘' + Style.RESET_ALL)\
                .encode('utf-8')

        output.append(line)
    return "\n".join(output)

#
# that's everything we need to save (and to load later)
# 
示例9
def default_log_template(self, record):
    """Return the prefix for the log message. Template for Formatter.

    :param: record: :py:class:`logging.LogRecord` object. this is passed in
    from inside the :py:meth:`logging.Formatter.format` record.

    """

    reset = [Style.RESET_ALL]
    levelname = [
        LEVEL_COLORS.get(record.levelname), Style.BRIGHT,
        '(%(levelname)s)',
        Style.RESET_ALL, ' '
    ]
    asctime = [
        '[', Fore.BLACK, Style.DIM, Style.BRIGHT,
        '%(asctime)s',
        Fore.RESET, Style.RESET_ALL, ']'
    ]
    name = [
        ' ', Fore.WHITE, Style.DIM, Style.BRIGHT,
        '%(name)s',
        Fore.RESET, Style.RESET_ALL, ' '
    ]
    threadName = [
        ' ', Fore.BLUE, Style.DIM, Style.BRIGHT,
        '%(threadName)s ',
        Fore.RESET, Style.RESET_ALL, ' '
    ]

    tpl = "".join(reset + levelname + asctime + name + threadName + reset)

    return tpl 
示例10
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 
示例11
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 
示例12
def m_info(self, m):
        m = '[*] ' + m
        if COLORAMA:
            print Style.DIM + m
        else:
            print m 
示例13
def m_info(self, m):
        m = '[*] ' + m
        if COLORAMA:
            print Style.DIM + m
        else:
            print m 
示例14
def m_info(self, m):
        m = '[*] ' + m
        if COLORAMA:
            print Style.DIM + m
        else:
            print m 
示例15
def banner():

    banner = Style.DIM + """  
__  ___ __ ___ | |_ __ _ __   ___      
\ \/ / '_ ` _ \| | '__| '_ \ / __|____ 
 >  <| | | | | | | |  | |_) | (_|_____|
/_/\_\_| |_| |_|_|_|  | .__/ \___|     
                      |_|              
 _                _        __                         
| |__  _ __ _   _| |_ ___ / _| ___  _ __ ___ ___ _ __ 
| '_ \| '__| | | | __/ _ \ |_ / _ \| '__/ __/ _ \ '__|
| |_) | |  | |_| | ||  __/  _| (_) | | | (_|  __/ |   
|_.__/|_|   \__,_|\__\___|_|  \___/|_|  \___\___|_|   """ + Style.RESET_ALL    
    print("{}".format(banner)) 
示例16
def description():
    print('=' * LINE_SIZE)

    title = Icons.BOOK + ' Lightnovel Crawler ' + \
        Icons.CLOVER + os.getenv('version')
    padding = ' ' * ((LINE_SIZE - len(title)) // 2)
    print(Fore.YELLOW, padding + title, Fore.RESET)

    desc = 'https://github.com/dipu-bd/lightnovel-crawler'
    padding = ' ' * ((LINE_SIZE - len(desc)) // 2)
    print(Style.DIM, padding + desc, Style.RESET_ALL)

    print('-' * LINE_SIZE)
# end def 
示例17
def _reverse_palette(code):
    return {
        1 : Fore.BLACK + _back_color(code),
        2 : Style.DIM
    } 
示例18
def log(message, color=Fore.BLUE):
    print(f'{color}{Style.DIM}[*] {Style.NORMAL}{Fore.LIGHTBLUE_EX}{message}') 
示例19
def main():
    init()

    log(f'Starting {Fore.MAGENTA}{Style.DIM}PyNubank{Style.NORMAL}{Fore.LIGHTBLUE_EX} context creation.')

    device_id = generate_random_id()

    log(f'Generated random id: {device_id}')

    cpf = input(f'[>] Enter your CPF(Numbers only): ')
    password = getpass('[>] Enter your password (Used on the app/website): ')

    generator = CertificateGenerator(cpf, password, device_id)

    log('Requesting e-mail code')
    try:
        email = generator.request_code()
    except NuException:
        log(f'{Fore.RED}Failed to request code. Check your credentials!', Fore.RED)
        return

    log(f'Email sent to {Fore.LIGHTBLACK_EX}{email}{Fore.LIGHTBLUE_EX}')
    code = input('[>] Type the code received by email: ')

    cert1, cert2 = generator.exchange_certs(code)

    save_cert(cert1, 'cert.p12')

    print(f'{Fore.GREEN}Certificates generated successfully. (cert.pem)')
    print(f'{Fore.YELLOW}Warning, keep these certificates safe (Do not share or version in git)') 
示例20
def process_item(self, item, spider):
        print('%s%s%s %s%s (%s %s%s%s, %s)' %
              (Fore.GREEN,
               item['hash_id'][:10],
               Fore.RESET+Style.BRIGHT,
               item['offer'],
               Style.RESET_ALL,
               item['currency'],
               Fore.YELLOW+Style.DIM,
               item['price'],
               Fore.RESET+Style.RESET_ALL,
               item['discount'] if 'discount' in item else '?'))
        return item 
示例21
def __download_album(self, album):
        """
        下载单个相册
        :param album: 相册数据
        :return: None
        """
        # 相册所有图片的id
        all_photo_ids = WeiboApi.fetch_photo_ids(self.uid, album['album_id'], album['type'])
        self.logger.info(Fore.BLUE + '检测到 %d 张图片' % len(all_photo_ids))

        # 相册所有大图的数据
        all_large_pics = self.__fetch_large_pics(album, all_photo_ids)
        total = len(all_large_pics)

        # 下载所有大图
        with concurrent.futures.ThreadPoolExecutor() as executor:
            album_path = self.__make_album_path(album)

            future_to_large = {
                executor.submit(self.__download_pic, large, album_path): large
                for large in all_large_pics
            }

            for i, future in enumerate(concurrent.futures.as_completed(future_to_large)):
                large = future_to_large[future]
                count_msg = '%d/%d ' % (i + 1, total)
                try:
                    result, path = future.result()
                except Exception as exc:
                    err = '%s 抛出了异常: %s' % (WeiboApi.make_large_url(large), exc)
                    self.logger.error(''.join([Fore.RED, count_msg, err]))
                else:
                    style = result and Style.NORMAL or Style.DIM
                    self.logger.info(''.join([Fore.GREEN, style, count_msg, path]))
            else:
                self.logger.info(Fore.BLUE + '《%s》 已完成' % album['caption']) 
示例22
def chitchat(self, msg, eol=None):
    if msg: print(Style.DIM + msg + Style.RESET_ALL, end=eol)
    sys.stdout.flush()

  # show warning message 
示例23
def errmsg(self, msg, info=""):
    info = str(info).strip()
    if info: # monkeypatch to make python error message less ugly
      info = item(re.findall('Errno -?\d+\] (.*)', info), '') or info.splitlines()[-1]
      info = Style.RESET_ALL + Style.DIM + " (" + info.strip('<>') + ")" + Style.RESET_ALL
    if msg: print(Back.RED + msg + info)

  # show printer and status 
示例24
def psfind(self, name):
    vol = Style.DIM + Fore.YELLOW + item(re.findall("^(%.*%)", name)) + Style.RESET_ALL
    name = Fore.YELLOW + const.SEP + re.sub("^(%.*%)", '', name) + Style.RESET_ALL
    print("%s %s" % (vol, name))

  # show directory listing 
示例25
def psdir(self, isdir, size, mtime, name, otime):
    otime = Style.DIM + "(created " + otime + ")" + Style.RESET_ALL 
    vol = Style.DIM + Fore.YELLOW + item(re.findall("^(%.*%)", name)) + Style.RESET_ALL
    name = re.sub("^(%.*%)", '', name) # remove volume information from filename
    name = Style.BRIGHT + Fore.BLUE + name + Style.RESET_ALL if isdir else name
    if isdir: print("d %8s   %s %s %s %s" % (size, mtime, otime, vol, name))
    else:     print("- %8s   %s %s %s %s" % (size, mtime, otime, vol, name))

  # show directory listing 
示例26
def pcldir(self, size, mtime, id, name):
    id = Style.DIM + "(macro id: " + id + ")" + Style.RESET_ALL
    print("- %8s   %s %s %s" % (size, mtime, id, name))

  # show output from df 
示例27
def print_res(path, match, val):
    """ Printing Results - Censys.io """
    sep = ' '
    pre = '[...]'
    post = pre
    pos = match.lower().index(val.lower())
    if len(match) >= 80:
        if pos < 35:
            pre = ''
        match_c = Style.DIM + pre + match[pos - 35:pos] + Fore.RED + Style.BRIGHT + match[
                                                                                    pos:pos + len(
                                                                                        val)] + \
                  Style.RESET_ALL + Style.DIM + match[
                                                pos + len(val):pos + 35] + post + Style.RESET_ALL
        match = pre + match[pos - 35:pos + 35] + post
    else:
        match_c = Style.DIM + match[:pos] + Fore.RED + Style.BRIGHT + match[pos:pos + len(val)] + \
                  Style.RESET_ALL + Style.DIM + match[pos + len(val):] + Style.RESET_ALL

    match_c = match_c.replace('\n', '\\n')
    match_c = match_c.replace('\r', '\\r')
    match = match.replace('\n', '\\n')
    match = match.replace('\r', '\\r')

    if len(path) >= 60:
        sep = '\n\t'
    if sys.stdout.isatty():
        print("  %s:%s%s" % (path, sep, match_c))
    else:
        print("  %s:%s%s" % (path, sep, match)) 
示例28
def say(message):
    print(prefix + Style.DIM + message + Style.RESET_ALL) 
示例29
def print_table(currency, data, directions, marktcap_spark, config): # pylint: disable=too-many-locals
    """
    Generate main table. Use specified <currency> as the main unit.
    """

    market_cap_direction, vol_24h_direction, btc_dominance_direction = directions

    currency_symbol = currencies_names.SYMBOL.get(currency, '')
    currency_suffix = ''
    if currency_symbol == '':
        currency_suffix = ' ' + currency

    market_cap = locale.format(
        "%d",
        int(data['marketcap_global_data']['total_market_cap_usd']),
        grouping=True)
    market_cap = currency_symbol + market_cap + currency_suffix
    market_cap += ' ' + colorize_direction(market_cap_direction)

    vol_24h = locale.format(
        "%d",
        int(data['marketcap_global_data']['total_24h_volume_usd']),
        grouping=True)
    vol_24h = currency_symbol + vol_24h + currency_suffix
    vol_24h += ' ' + colorize_direction(vol_24h_direction)

    btc_dominance = '%2.1f%%' % data['marketcap_global_data']['bitcoin_percentage_of_market_cap']
    btc_dominance += ' ' + colorize_direction(btc_dominance_direction)

    header = [
        'Rank',
        'Coin',
        'Price (%s)' % currency,
        'Change (24H)',
        'Change (1H)',
        'Market Cap (%s)' % currency,
        'Spark (1H)'
        ]
    table_class = WindowsTable
    table = table_class(
        [[colored(x, 'yellow') for x in header]]
        + _colorize_entries(data['data']))
    table.inner_row_border = True

    header = HEADER.replace('Z'*48, marktcap_spark)

    output = []
    output += [colored("\n".join(header.splitlines()[1:]) + "\n", 'green')]
    output += ["Market Cap: %s\n24h Vol: %s\nBTC Dominance: %s" \
                % (market_cap, vol_24h, btc_dominance)]
    output += [_colorize_frame(table.table)]
    output += [Fore.WHITE + Style.DIM + "%s" % data['timestamp_now']  + Style.RESET_ALL]
    output += [""]

    if not config.get('no-follow-line'):
        output += [MSG_NEW_FEATURE]
        output += [MSG_FOLLOW_ME + MSG_GITHUB_BUTTON]

    return "\n".join(output) + "\n" 
示例30
def debug_log_template(self, record):
    """ Return the prefix for the log message. Template for Formatter.

    :param: record: :class:`logging.LogRecord` object. this is passed in
    from inside the :py:meth:`logging.Formatter.format` record.

    """

    reset = [Style.RESET_ALL]
    levelname = [
        LEVEL_COLORS.get(record.levelname), Style.BRIGHT,
        '(%(levelname)1.1s)',
        Style.RESET_ALL, ' '
    ]
    asctime = [
        '[', Fore.BLACK, Style.DIM, Style.BRIGHT,
        '%(asctime)s', Fore.RESET, Style.RESET_ALL, ']'
    ]
    name = [
        ' ', Fore.WHITE, Style.DIM, Style.BRIGHT,
        '%(name)s',
        Fore.RESET, Style.RESET_ALL, ' '
    ]
    threadName = [
        ' ', Fore.BLUE, Style.DIM, Style.BRIGHT,
        '%(threadName)s ',
        Fore.RESET, Style.RESET_ALL, ' '
    ]
    module_funcName = [
        Fore.GREEN, Style.BRIGHT,
        '%(module)s.%(funcName)s()'
    ]
    lineno = [
        Fore.BLACK, Style.DIM, Style.BRIGHT, ':', Style.RESET_ALL,
        Fore.CYAN, '%(lineno)d'
    ]

    tpl = ''.join(
        reset + levelname + asctime + name + threadName + module_funcName +
        lineno + reset
    )

    return tpl