Python colorama.Style 模块,BRIGHT 实例源码

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

项目: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)
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def option(question, options, default=1):
    print(question)
    options = list(options)
    for idx, element in enumerate(options):
        print("{}) {}".format(idx+1,element))
    while True:
        i = input("{Style.BRIGHT}{Fore.BLUE}:: {Fore.RESET}Please pick[{}]: {Style.RESET_ALL}".format(default, Style=Style, Fore=Fore))
        try:
            if i == "":
                i = default
            else:
                i = int(i)
            if 0 < i <= len(options):
                return options[i-1]
        except:
            pass
    return None
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def size():
    cache_dir = cfg.cache.dir
    source_dir = cfg.source.dir

    cache_size = 0
    for f in cache_dir.walkfiles():
        cache_size += f.size

    source_size = 0
    for f in source_dir.walkfiles():
        source_size += f.size

    print("{Style.BRIGHT}Cache: {Style.RESET_ALL} {}".format(
        humanize.naturalsize(cache_size, binary=True),
        Style=Style
    ))
    print("{Style.BRIGHT}Source:{Style.RESET_ALL} {}".format(
        humanize.naturalsize(source_size, binary=True),
        Style=Style
    ))
项目: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
项目:binarly-query    作者:binarlyhq    | 项目源码 | 文件源码
def process_search(options):
    search_query = []
    search_query.extend([hex_pattern(val.replace(' ', '')) for val in options.hex])
    search_query.extend([ascii_pattern(val) for lst in options.a for val in lst])
    search_query.extend([wide_pattern(val) for lst in options.w for val in lst])

    result = BINOBJ.search(
        search_query, limit=options.limit, exact=options.exact, test=options.test)
    if 'error' in result:
        print(Style.BRIGHT + Fore.RED + result['error']['message'])
        return

    if 'stats' in result:
        show_stats_new(result['stats'], options.limit)

    if len(result['results']) == 0:
        return

#    if len(result['results']) >= options.limit:
#        print("Showing top {0} results:".format(options.limit))
#    else:
#        print("Results:")

    show_results(result['results'], pretty_print=options.pretty_print)
项目:python-ansimarkup    作者:gvalkov    | 项目源码 | 文件源码
def test_unknown_tags():
    assert p('<tag>1</tag>') == '<tag>1</tag>'
    assert p('<tag>') == '<tag>'
    assert p('</tag>') == '</tag>'

    assert p('<b>1</b><tag>2</tag>') == S.BRIGHT + '1' + S.RESET_ALL + '<tag>2</tag>'
    assert p('<tag>1</tag><b>2</b>') == '<tag>1</tag>' + S.BRIGHT + '2' + S.RESET_ALL

    assert p('<b>1</b><tag>2</tag><b>3</b>') == S.BRIGHT + '1' + S.RESET_ALL + '<tag>2</tag>' + S.BRIGHT + '3' + S.RESET_ALL
    assert p('<tag>1</tag><b>2</b><tag>3</tag>') == '<tag>1</tag>' + S.BRIGHT + '2' + S.RESET_ALL + '<tag>3</tag>'

    assert p('<b><tag>1</tag></b>') == S.BRIGHT + '<tag>1</tag>' + S.RESET_ALL
    assert p('<tag><b>1</b></tag>') == '<tag>' + S.BRIGHT + '1' + S.RESET_ALL + '</tag>'

    assert p('<b><tag>1</tag>') == S.BRIGHT + '<tag>1</tag>'
    assert p('<tag>1</tag><b>') == '<tag>1</tag>' + S.BRIGHT

    assert p('<b><tag>') == S.BRIGHT + '<tag>'
    assert p('<tag><b>') == "<tag>" + S.BRIGHT

    assert p('<b></tag>') == S.BRIGHT + '</tag>'
    assert p('</tag><b>') == "</tag>" + S.BRIGHT
项目:python-ansimarkup    作者:gvalkov    | 项目源码 | 文件源码
def test_tag_chars():
    with raises(ValueError):
        am = AnsiMarkup(tag_sep='{')

    with raises(ValueError):
        am = AnsiMarkup(tag_sep='(-)')

    with raises(ValueError):
        am = AnsiMarkup(tag_sep='qq')

    am = AnsiMarkup(tag_sep='{}')

    r1 = p('0<b>1<d>2</d>3</b>4')
    r2 = am.parse('0{b}1{d}2{/d}3{/b}4')
    assert r1 == r2 == '0' + S.BRIGHT + '1' + S.DIM + '2' + S.RESET_ALL + S.BRIGHT + '3' + S.RESET_ALL + '4'

    assert s('<b>1</b>') == am.strip('{b}1{/b}') == '1'
项目:Auto-Amazon-Giveaways    作者:zdrouse    | 项目源码 | 文件源码
def instant_giveaway(prize_name):
    global won_giveaways, lost_giveaways
    giveaway_box = chromedriver.find_element_by_id(instant_box)
    giveaway_box.click()
    time.sleep(10)
    get_result = chromedriver.find_element_by_id('title')
    time.sleep(5)
    if "you didn't win" in get_result.text:
        lost_giveaways += 1
        print(Fore.YELLOW + Style.BRIGHT + '\n    **** You did not win: %s' % prize_name)
        time.sleep(5)
    elif "you're a winner!" in get_result.text:
        won_giveaways += 1
        print(Fore.GREEN + Style.BRIGHT + '\n    **** Winner Winner! Chicken Dinner!: %s' % prize_name)
        time.sleep(1)
        playsound('.\sounds\\btyswt.mp3')
        time.sleep(5)
    else:
        print(Fore.RED + Style.BRIGHT + '\n    ---- UNRECOGNIZED RESPONSE FOR: %s' % prize_name)

# function to process the 'None' requirement giveaways.
项目: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)
项目:pixie    作者:algorithm-ninja    | 项目源码 | 文件源码
def __init__(self, ethers_path, static_ethers, wipe):
        """
        :param ethers_path: path to the ethers file
        :param static_ethers: path to static ethers file (only when wiping)
        :param wipe: wipe the ethers
        """
        self.ethers_path = ethers_path
        self.wipe = wipe
        self.ethers = {}

        EthersManager.assert_writable(self.ethers_path)

        if wipe:
            print(Fore.RED + Style.BRIGHT + "The ethers file will be wiped!")
            if static_ethers:
                print(Fore.BLUE + "The static ethers will be loaded")
                self.load_ethers(static_ethers)
            else:
                print(Fore.BLUE + "The ethers file will be created from scratch")
        else:
            self.load_ethers(self.ethers_path)
项目:TorStat    作者:rootlabs    | 项目源码 | 文件源码
def TOR_PROC_CHECK():
    isTorRunnin = False
    TOR_INFO = {}
    TOR_PROC = None
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name'])
        except psutil.NoSuchProcess:
            pass
        else:
            if pinfo['name'] == "tor":
                isTorRunnin = True
                TOR_INFO['pid'] = pinfo['pid']
                TOR_INFO['name'] = pinfo['name']
                break

    if isTorRunnin == True:
        print ("[" + Fore.GREEN + Style.BRIGHT + "+" + Style.RESET_ALL + "]" + Fore.GREEN + Style.BRIGHT + " Tor is running." + Style.RESET_ALL)
        TOR_PROC = psutil.Process(int(TOR_INFO['pid']))
        return TOR_PROC
    else:
        print ("[" + Fore.RED + Style.BRIGHT + "-" + Style.RESET_ALL + "]" + Fore.RED + Style.BRIGHT + " Tor is not running." + Style.RESET_ALL)
        exit()
项目:TorStat    作者:rootlabs    | 项目源码 | 文件源码
def TABLE_PRETTYPRINT(TOR_PROC):
    AF_INET6 = getattr(socket, 'AF_INET6', object())
    PMAP = {
        (AF_INET, SOCK_STREAM): 'tcp',
        (AF_INET6, SOCK_STREAM): 'tcp6',
        (AF_INET, SOCK_DGRAM): 'udp',
        (AF_INET6, SOCK_DGRAM): 'udp6',
    }

    print (Fore.BLUE + Style.BRIGHT +"\t=> Process name : %s\n\t=> PID : %s"%(TOR_PROC.name(),TOR_PROC.pid))
    print Style.RESET_ALL
    templete = "%-15s %-25s %-25s %s"
    print (templete % ("Proto", "Local address", "Remote address", "Status"))
    print (templete % ("=====", "=============", "==============", "======"))
    for attr in TOR_PROC.connections(kind='inet'):
        LADDR = "%s:%s"%(attr.laddr)
        RADDR = None
        if attr.raddr:
            RADDR = "%s:%s"%(attr.raddr)
        print (templete % (PMAP[(attr.family, attr.type)], LADDR, RADDR or '-', attr.status))   
    print
项目:CManager    作者:fachrioktavian    | 项目源码 | 文件源码
def show_help(self):
        help = 'dashboard section:\n'
        help += ' show interfaces          : Print all interfaces found by cmanager\n'
        help += ' wizard wifi              : Go to wifi wizard section\n'
        help += ' exit                     : Exit cmanager\n\n'
        help += 'wifi-wizard section:\n'
        help += ' show profile             : List profile that saved by cmanager\n'
        help += ' show options             : List available options used to create a profile\n'
        help += ' set [options] [value]    : Set value to available options before save the profile\n'
        help += ' save profile             : Save profile after options data\'s been filled\n'
        help += ' del profile [profile]    : Del profile by profile\'s name\n'
        help += ' use [wireless_intarface] : Use this command BEFORE scanning available network or connecting a profile\n'
        help += ' scan                     : Scanning available networks\n'
        help += ' connect [profile]        : Connecting wireless interface to a wifi network using specified profile\'s name\n'
        help += ' back                     : Back to dashboard section'

        print (Fore.GREEN + Style.BRIGHT + help)
项目:blacklion    作者:Foohx    | 项目源码 | 文件源码
def log(self, prefix, text, line=False):
        now = datetime.now()
        message = ""
        if prefix == '?':
            c = Fore.CYAN
        elif prefix == '+':
            c = Fore.GREEN
        elif prefix == '-':
            c = Fore.RED
        elif prefix == '!':
            c = Fore.YELLOW
        c = Style.BRIGHT + c
        e = Style.RESET_ALL + Fore.RESET
        if line:
            print c+"["+now.strftime("%Y-%m-%d %H:%M:%S")+"]["+prefix+"] "+text+e
        else :
            print "["+now.strftime("%Y-%m-%d %H:%M:%S")+"]["+c+prefix+e+"] "+text
项目:blacklion    作者:Foohx    | 项目源码 | 文件源码
def log(prefix, text, line=False):
    now = datetime.now()
    message = ""
    if prefix == '?':
        c = Fore.CYAN
    elif prefix == '+':
        c = Fore.GREEN
    elif prefix == '-':
        c = Fore.RED
    elif prefix == '!':
        c = Fore.YELLOW
    c = Style.BRIGHT + c
    e = Style.RESET_ALL + Fore.RESET
    if line:
        print c+"["+now.strftime("%Y-%m-%d %H:%M")+"]["+prefix+"] "+text+e
    else :
        print "["+now.strftime("%Y-%m-%d %H:%M")+"]["+c+prefix+e+"] "+text
项目:InstagramBot    作者:JagdeepThakur    | 项目源码 | 文件源码
def get_comment_list(insta_username) :

    media_id=get_post_id(insta_username)
    request_url=BASE_URL+"media/%s/comments/?access_token=%s"%(media_id,APP_ACCESS_TOKEN)
    print "Get Requested URL:%s"%(request_url)
    comment_info=requests.get(request_url).json()

    if comment_info['meta']['code']==200 :
        if len(comment_info['data']) :
            for x in range(0,len(comment_info['data'])) :
                comment_id=comment_info['data'][x]['id']
                comment_text=comment_info['data'][x]['text']
                print Fore.BLUE+Style.BRIGHT+"Comments are %s"%(comment_text)
        else:
            print "there is no comment regarding this post"
    else :
        print "status code other than 200 found"
项目:py-backwards    作者:nvbn    | 项目源码 | 文件源码
def compilation_result(result: CompilationResult) -> str:
    if result.dependencies:
        dependencies = ('\n  Additional dependencies:\n'
                        '{bright}    {dependencies}{reset}').format(
            dependencies='\n    '.join(dep for dep in result.dependencies),
            bright=Style.BRIGHT,
            reset=Style.RESET_ALL)
    else:
        dependencies = ''

    return ('{bright}Compilation succeed{reset}:\n'
            '  target: {bright}{target}{reset}\n'
            '  files: {bright}{files}{reset}\n'
            '  took: {bright}{time:.2f}{reset} seconds{dependencies}').format(
        bright=Style.BRIGHT,
        reset=Style.RESET_ALL,
        target='{}.{}'.format(*result.target),
        files=result.files,
        time=result.time,
        dependencies=dependencies)
项目: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
项目:operative-framework    作者:graniet    | 项目源码 | 文件源码
def export_search(self, get_all, word):
        if self.finded == 0:
            print "------------------------------------"
        self.finded = 1
        nb_result = len(get_all)
        if get_all not in self.result:
            count = 0
            for line in get_all:
                if ")" in line:
                    line = line.replace(')','')
                if line.strip() != "":
                    count += 1
                    if word in line.strip():
                        string = Fore.RED + Style.BRIGHT + word + Style.RESET_ALL
                        line = line.replace(word,string)
                    print "data "+str(count)+": "+line.strip()
            print "------------------------------------"
            self.result.append(get_all)
项目:operative-framework    作者:graniet    | 项目源码 | 文件源码
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
项目:operative-framework    作者:graniet    | 项目源码 | 文件源码
def loading():
    red_bold = Style.BRIGHT + Fore.RED
    reset = Style.RESET_ALL
    loading = "loading the fingerprinting framework"
    action = 0
    while action < 1:
        for i,char in enumerate(loading):
            if i == 0:
                print "%s%s%s%s" %(red_bold,char.upper(),reset,loading[1:])
            elif i == 1:
                old_loading = loading[0].lower()
                print "%s%s%s%s%s" %(old_loading,red_bold,char.upper(),reset,loading[2:])
            elif i == i:
                old_loading = loading[-0:i].lower()
                print "%s%s%s%s%s" %(old_loading,red_bold,char.upper(),reset,loading[i+1:])
            time.sleep(0.1)
            os.system('clear')
        action += 1
    return True
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def print_yellow(string):
    if windows_client(): reinit()
    print (Fore.YELLOW + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def print_blue(string):
    if windows_client(): reinit()
    print (Fore.BLUE + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def print_cyan(string):
    if windows_client(): reinit()
    print (Fore.CYAN + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def print_green(string):
    if windows_client(): reinit()
    print (Fore.GREEN + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
def print_red(string):
    if windows_client(): reinit()
    print (Fore.RED + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def yes_no(question, default="yes"):
    """Ask a yes/no question via input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True,
             "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(Style.BRIGHT + Fore.BLUE + ":: " + Fore.RESET + question + prompt + Style.NORMAL)
        choice = input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def set_(name, value):
    section, option = name.split(".")
    try:
        cfg[section][option] = value
    except KeyError:
        print(
            "Unknown config option {Style.BRIGHT}{}{Style.RESET_ALL}"
            .format(
                name,
                Style=Style
            )
        )
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def get(name):
    section, option = name.split(".")
    try:
        print(cfg[section][option])
    except KeyError:
        print(
            "Unknown config option {Style.BRIGHT}{}{Style.RESET_ALL}"
            .format(
                name,
                Style=Style
            )
        )
项目:binarly-query    作者:binarlyhq    | 项目源码 | 文件源码
def show_row(row):
    row = color_row(row)
    print(" ".join(["%s%s%s:%s" % (Style.NORMAL, x.capitalize(), Style.BRIGHT, y) for (x, y) in row.items()]))
项目:binarly-query    作者:binarlyhq    | 项目源码 | 文件源码
def process_classify(options):
    if os.path.exists(options.files[0]):
        filelist = options.files
        if os.path.isdir(options.files[0]):
            filelist = get_filelist(filelist[0])

        result = BINOBJ.classify_files(
            filelist, upload_missing=options.u, status_callback=my_callback)
    else:
        result = BINOBJ.classify_hashes(options.files)

    if 'error' in result or result['status'] != 'done':
        print(Style.BRIGHT + Fore.RED + "Request failed")
    else:
        print("Classification Results:")

    reqid = result.get('results', None)
    if reqid is None:
        # the request failed before any files could be analyzed
        print(Style.BRIGHT + Fore.RED +
              "Fail reason: {0} (error code={1})".format(
                  result['error']['message'], result['error']['code']))
        return

    classify_data = []
    for key, value in result['results'].iteritems():
        status = Style.RESET_ALL + Fore.GREEN + "OK" + Style.RESET_ALL
        if 'error' in value:
            status = Fore.RED + value['error']['message'] + Style.RESET_ALL
        row = {'SHA1': key, 'label': value.get('label', '.'), 'family': value.get('family', '.'), 'Status': status}

        classify_data.append(row)

    if options.pretty_print:
        show_results(classify_data, pretty_print=options.pretty_print)
    else:
        print("-" * 100)
        for row in classify_data:
            show_row(row)
    return
项目:binarly-query    作者:binarlyhq    | 项目源码 | 文件源码
def process_hunt(options):
    result = BINOBJ.yara_hunt(options.yarafile, options.test, my_callback)
    if 'error' in result or result['status'] != 'done':
        print(Style.BRIGHT + Fore.RED + "Request failed.")
        print(Style.BRIGHT + Fore.RED +
              "Fail reason: {0} (error code={1})".format(
                  result['error']['message'], result['error']['code']))
        return

    if 'stats' in result:
        show_stats(result['stats'])

    if len(result['results']) > 0:
        show_results(result['results'], pretty_print=options.pretty_print)
项目:binarly-query    作者:binarlyhq    | 项目源码 | 文件源码
def process_metadata(options):
    result = BINOBJ.get_metadata(options.filehash)
    if 'error' in result:
        print(Style.BRIGHT + Fore.RED + result['error']['message'])
        return

    dump(result[options.filehash])
项目:python-ansimarkup    作者:gvalkov    | 项目源码 | 文件源码
def test_basic(caplog):
    log, hdl = caplog

    log.info('<b>1</b>')
    assert hdl.last_msg == S.BRIGHT + '1' + S.RESET_ALL
项目:python-ansimarkup    作者:gvalkov    | 项目源码 | 文件源码
def test_flat():
    assert p('<b>1</b>') == p('<bold>1</bold>') == S.BRIGHT + '1' + S.RESET_ALL
    assert p('<d>1</d>') == p('<dim>1</dim>')   == S.DIM    + '1' + S.RESET_ALL

    assert p('<b>1</b><d>2</d>')  == S.BRIGHT + '1' + S.RESET_ALL    +    S.DIM + '2' + S.RESET_ALL
    assert p('<b>1</b>2<d>3</d>') == S.BRIGHT + '1' + S.RESET_ALL + '2' + S.DIM + '3' + S.RESET_ALL
项目:python-ansimarkup    作者:gvalkov    | 项目源码 | 文件源码
def test_flat_colors():
    assert p('<r>1</r>') == p('<red>1</red>') == p('<fg red>1</fg red>') == F.RED + '1' + S.RESET_ALL
    assert p('<R>1</R>') == p('<RED>1</RED>') == p('<bg red>1</bg red>') == B.RED + '1' + S.RESET_ALL

    assert p('<r,y>1</r,y>') == p('<red,yellow>1</red,yellow>') == F.RED + B.YELLOW + '1' + S.RESET_ALL
    assert p('<b,r,y>1</b,r,y>') == p('<bold,red,yellow>1</bold,red,yellow>') == S.BRIGHT + F.RED + B.YELLOW + '1' + S.RESET_ALL
    assert p('<b,r,>1</b,r,>') == p('<bold,red,>1</bold,red,>') == S.BRIGHT + F.RED + '1' + S.RESET_ALL

    assert p('<fg RED>1</fg RED>') == '<fg RED>1</fg RED>'
    assert p('<fg light-blue2>1</fg light-blue2>') == '<fg light-blue2>1</fg light-blue2>'

    assert p('<bg ,red>1</bg ,red>') == '<bg ,red>1</bg ,red>'
    assert p('<bg red,>1</bg red,>') == '<bg red,>1</bg red,>'
    assert p('<bg a,z>1</bg a,z>') == '<bg a,z>1</bg a,z>'
    assert p('<bg blue,yelllow>1</bg blue,yelllow>') == '<bg blue,yelllow>1</bg blue,yelllow>'
    assert p('<bg r, y>1</bg r, y>') == '<bg r, y>1</bg r, y>'

    assert p('<>1</>') == '<>1</>'
    assert p('</>1</>') == '</>1</>'
    assert p('<,>1</,>') == '<,>1</,>'
    assert p('<,,>1</,,>') == '<,,>1</,,>'
    assert p('<z,z>1</z,z>') == '<z,z>1</z,z>'
    assert p('<z,z,z>1</z,z,z>') == '<z,z,z>1</z,z,z>'

    assert p('<red,RED>1</red,RED>') == '<red,RED>1</red,RED>'
    assert p('<bold,red>1</bold,red>') == '<bold,red>1</bold,red>'
    assert p('<b,red,RED>1</b,red,RED>') == '<b,red,RED>1</b,red,RED>'
    assert p('<b,red,bold>1</b,red,bold>') == '<b,red,bold>1</b,red,bold>'
    assert p('<b,,>1</b,,>') == '<b,,>1</b,,>'
    assert p('<b,a,>1</b,a,>') == '<b,a,>1</b,a,>'
    assert p('<b,,z>1</b,,z>') == '<b,,z>1</b,,z>'
项目:python-ansimarkup    作者:gvalkov    | 项目源码 | 文件源码
def test_nested():
    assert p('0<b>1<d>2</d>3</b>4') == '0' + S.BRIGHT + '1' + S.DIM + '2' + S.RESET_ALL + S.BRIGHT + '3' + S.RESET_ALL + '4'
    assert p('<d>0<b>1<d>2</d>3</b>4</d>') == S.DIM + '0' + S.BRIGHT + '1' + S.DIM + '2' + S.RESET_ALL + S.DIM + S.BRIGHT + '3' + S.RESET_ALL + S.DIM +'4' + S.RESET_ALL
项目:python-ansimarkup    作者:gvalkov    | 项目源码 | 文件源码
def test_usertags():
    user_tags = {
        'info':  F.GREEN + S.BRIGHT,
        'info1': p('<g><b>'),
        'call': lambda: F.BLUE + B.RED
    }
    am = AnsiMarkup(tags=user_tags)

    assert am.parse('<info>1</info>') == F.GREEN + S.BRIGHT + '1' + S.RESET_ALL
    assert am.parse('<info>1</info>') == am.parse('<info1>1</info1>')
    assert am.parse('<call>1</call>') == F.BLUE  + B.RED + '1' + S.RESET_ALL
    assert am.strip('<info1>1</info1>') == '1'
项目:MailFail    作者:m0rtem    | 项目源码 | 文件源码
def tor_test():
    # Get Tor IP from wtfismyip
    try:
        with urllib.request.urlopen('https://wtfismyip.com/text') as response:
            html = response.read()
            print_out(Style.BRIGHT + Fore.GREEN + "Your Tor IP is: " + html.decode('utf-8'))
    except HTTPError as e:
        # do something
        print_out(Style.BRIGHT + Fore.RED + "Error code: " + str(e.code))
        exit(1)
    except URLError as e:
        # do something
        print_out(Style.BRIGHT + Fore.RED + "Reason: " + str(e.reason))
        exit(1)
项目:pixie    作者:algorithm-ninja    | 项目源码 | 文件源码
def assert_writable(path):
        if not os.access(path, os.W_OK):
            print(Fore.RED + Style.BRIGHT + "ERROR: %s is not writable" % path, file=sys.stderr)
            sys.exit(1)
项目:pixie    作者:algorithm-ninja    | 项目源码 | 文件源码
def assert_readable(path):
        if not os.access(path, os.R_OK):
            print(Fore.RED + Style.BRIGHT + "ERROR: %s is not readable" % path, file=sys.stderr)
            sys.exit(1)
项目:pixie    作者:algorithm-ninja    | 项目源码 | 文件源码
def export_ethers(self):
        lines = ["%s %s" % (mac, ip) for mac,ip in self.ethers.items()]

        print(Fore.GREEN + Style.BRIGHT + "Generated ethers file")
        self.print_boxed(lines)

        file = open(self.ethers_path, 'w')
        file.write('\n'.join(lines) + '\n')
        file.close()

        print(Fore.GREEN + "%s file written" % self.ethers_path)

        self.reload_services()
项目:pixie    作者:algorithm-ninja    | 项目源码 | 文件源码
def reload_services(self):
        print(Fore.GREEN + Style.BRIGHT + "Reloading services")

        print(Fore.GREEN + "SIGHUPing dnsmasq")
        call(['killall', '-s', 'SIGHUP', 'dnsmasq'])
项目:netutils-linux    作者:strizhechenko    | 项目源码 | 文件源码
def bright(string):
    return wrap(string, Style.BRIGHT)
项目:netutils-linux    作者:strizhechenko    | 项目源码 | 文件源码
def wrap_header(string):
    return wrap("# {0}\n".format(string), Style.BRIGHT)
项目:LibreNews-Server    作者:milesmcc    | 项目源码 | 文件源码
def ok(message, detail=""):
    level = Fore.GREEN + "[OK] " + Fore.RESET
    print(prefix + level + Style.BRIGHT + message + Style.RESET_ALL + " " + detail + Style.RESET_ALL)
项目:LibreNews-Server    作者:milesmcc    | 项目源码 | 文件源码
def warn(message, detail=""):
    level = Fore.YELLOW + "[WARN] " + Fore.RESET
    print(prefix  + level +  Style.BRIGHT + message + Style.RESET_ALL + " " + detail + Style.RESET_ALL)
项目:LibreNews-Server    作者:milesmcc    | 项目源码 | 文件源码
def error(message, detail=""):
    level = Fore.RED + "[ERR] " + Fore.RESET
    print(prefix + level +  Style.BRIGHT + message + Style.RESET_ALL + " " + detail + Style.RESET_ALL)
项目:paas-tools    作者:imperodesign    | 项目源码 | 文件源码
def run(self):
        data = self.request('avail.datacenters')
        column_format = "{:<4} {:}"
        print(Style.BRIGHT + Fore.GREEN + column_format.format(*('ID', 'LOCATION')) + Fore.RESET + Style.RESET_ALL)
        for data_center in data:
            row = (
                data_center.get('DATACENTERID'),
                data_center.get('LOCATION')
            )
            print(Fore.GREEN + column_format.format(*row) + Fore.RESET)
项目:paas-tools    作者:imperodesign    | 项目源码 | 文件源码
def run(self):
        data = self.request('avail.linodeplans')
        column_format = "{:<4} {:<16} {:<8} {:<12} {:}"
        print(Style.BRIGHT + Fore.GREEN + column_format.format(
            *('ID', 'LABEL', 'CORES', 'RAM', 'PRICE')) + Fore.RESET + Style.RESET_ALL)
        for plan in data:
            row = (
                plan.get('PLANID'),
                plan.get('LABEL'),
                plan.get('CORES'),
                str(plan.get('RAM')) + 'MB',
                '$' + str(plan.get('PRICE'))
            )
            print(Fore.GREEN + column_format.format(*row) + Fore.RESET)