• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python xtermcolor.colorize函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中xtermcolor.colorize函数的典型用法代码示例。如果您正苦于以下问题:Python colorize函数的具体用法?Python colorize怎么用?Python colorize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了colorize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: generate_license_file

def generate_license_file(license, owner):
    """ Generates a license file and populate it accordingly.
    Asks user for extra context variables if any in the license. 
    """

    template_file_path = join(dirname(__file__), "../data/template/%s.tmpl" %
                              (license))
    template_file = abspath(template_file_path)

    with open(template_file) as f:
        content = f.read()

    parsed_context = parse_template(content)
    default_context_keys = ['owner', 'year']

    context = {'year': datetime.now().year, 'owner': owner}
    extra_context = {}

    if (len(parsed_context) > len(default_context_keys)):
        for key in parsed_context:
            if key not in default_context_keys:
                print colorize(
                    "\n%s license also asks for %s. What do you want to fill there?"
                    % (license, key),
                    ansi=4)
                extra_context[key] = raw_input().strip()

    arguments = context.copy()
    arguments.update(extra_context)

    template = Template(content)
    content = template.render(arguments)
    with open('LICENSE', 'w') as f:
        f.write(content)
开发者ID:pravj,项目名称:lisense,代码行数:34,代码来源:new.py


示例2: load_relation

def load_relation(filename, defname=None):
    if not os.path.isfile(filename):
        print (colorize(
            "%s is not a file" % filename, ERROR_COLOR), file=sys.stderr)
        return None

    f = filename.split('/')
    if defname == None:
        defname = f[len(f) - 1].lower()
        if defname.endswith(".csv"):  # removes the extension
            defname = defname[:-4]

    if not rtypes.is_valid_relation_name(defname):
        print (colorize(
            "%s is not a valid relation name" % defname, ERROR_COLOR), file=sys.stderr)
        return
    try:
        relations[defname] = relation.relation(filename)

        completer.add_completion(defname)
        printtty(colorize("Loaded relation %s" % defname, 0x00ff00))
        return defname
    except Exception as e:
        print (colorize(e, ERROR_COLOR), file=sys.stderr)
        return None
开发者ID:chippography,项目名称:relational,代码行数:25,代码来源:linegui.py


示例3: cli

def cli():
    parser = argparse.ArgumentParser(description=description, epilog='Created by Scott Frazer (https://github.com/scottfrazer)', formatter_class=RawTextHelpFormatter)
    parser.add_argument('--version', action='version', version=str(pkg_resources.get_distribution('mdtoc')))
    parser.add_argument('markdown_file')
    parser.add_argument('--check-links', action='store_true', help="Find all hyperlinks and ensure that \nthey point to something valid")
    cli = parser.parse_args()
    cli.markdown_file = os.path.expanduser(cli.markdown_file)
    if not os.path.isfile(cli.markdown_file):
        sys.exit('File not found: {}'.format(cli.markdown_file))

    modify_and_write(cli.markdown_file)

    if cli.check_links:
        with open(cli.markdown_file) as fp:
            contents = fp.read()

        valid_http_fragments = ['#'+as_link(h) for (l, h) in headers(contents)]
        for (text, link, line, col) in get_links(contents):
            valid = 'unrecognized link type'
            if link.startswith('#'):
                if link not in valid_http_fragments:
                    valid = colorize('INVALID', ansi=1)
                else:
                    valid = colorize('VALID', ansi=2)
            elif link.startswith('http://') or link.startswith('https://'):
                r = requests.get(link)
                valid = 'Response: {}'.format(r.status_code)
            print('Checking {line}:{col} [{text}]({link}) --> {valid} '.format(
                text=colorize(text, ansi=3),
                link=colorize(link, ansi=4),
                line=line,
                col=col,
                valid=valid
            ))
开发者ID:scottfrazer,项目名称:mdtoc,代码行数:34,代码来源:main.py


示例4: main

def main(files=[]):
    printtty(colorize('> ', PROMPT_COLOR) + "; Type HELP to get the HELP")
    printtty(colorize('> ', PROMPT_COLOR) +
           "; Completion is activated using the tab (if supported by the terminal)")

    for i in files:
        load_relation(i)

    readline.set_completer(completer.complete)

    readline.parse_and_bind('tab: complete')
    readline.parse_and_bind('set editing-mode emacs')
    readline.set_completer_delims(" ")

    while True:
        try:

            line = input(colorize('> ' if TTY else '', PROMPT_COLOR))
            if isinstance(line, str) and len(line) > 0:
                exec_line(line)
        except KeyboardInterrupt:
            if TTY:
                print ('^C\n')
                continue
            else:
                break
        except EOFError:
            printtty()
            sys.exit(0)
开发者ID:chippography,项目名称:relational,代码行数:29,代码来源:linegui.py


示例5: exec_query

def exec_query(command):
    '''This function executes a query and prints the result on the screen
    if the command terminates with ";" the result will not be printed
    '''

    # If it terminates with ; doesn't print the result
    if command.endswith(';'):
        command = command[:-1]
        printrel = False
    else:
        printrel = True

    # Performs replacements for weird operators
    command = replacements(command)

    # Finds the name in where to save the query
    parts = command.split('=', 1)
    relname,query = maintenance.UserInterface.split_query(command)

    # Execute query
    try:
        pyquery = parser.parse(query)
        result = pyquery(relations)

        printtty(colorize("-> query: %s" % pyquery, 0x00ff00))

        if printrel:
            print ()
            print (result)

        relations[relname] = result

        completer.add_completion(relname)
    except Exception as e:
        print (colorize(str(e), ERROR_COLOR))
开发者ID:chippography,项目名称:relational,代码行数:35,代码来源:linegui.py


示例6: load_relation

def load_relation(filename: str, defname:Optional[str]=None) -> Optional[str]:
    '''
    Loads a relation into the set. Defname is the given name
    to the relation.

    Returns the name to the relation, or None if it was
    not loaded.
    '''
    if not os.path.isfile(filename):
        print(colorize(
            "%s is not a file" % filename, ERROR_COLOR), file=sys.stderr)
        return None

    if defname is None:
        f = filename.split('/')
        defname = f[-1].lower()
        if defname.endswith(".csv"):  # removes the extension
            defname = defname[:-4]

    if not rtypes.is_valid_relation_name(defname):
        print(colorize(
            "%s is not a valid relation name" % defname, ERROR_COLOR), file=sys.stderr)
        return None
    try:
        relations[defname] = relation.relation(filename)

        completer.add_completion(defname)
        printtty(colorize("Loaded relation %s" % defname, COLOR_GREEN))
        return defname
    except Exception as e:
        print(colorize(str(e), ERROR_COLOR), file=sys.stderr)
        return None
开发者ID:ltworf,项目名称:relational,代码行数:32,代码来源:linegui.py


示例7: run_fail_test

def run_fail_test(testname):
    '''Runs a test, which executes a query that is supposed to fail'''
    print ("Running fail test: " + colorize(testname, COLOR_MAGENTA))

    query = readfile('%s%s.fail' % (tests_path, testname)).strip()
    test_succeed = True

    try:
        expr = parser.parse(query)
        expr(rels)
        test_succeed = False
    except:
        pass

    try:
        o_query = optimizer.optimize_all(query, rels)
        o_expr = parser.parse(o_query)
        o_expr(rels)
        test_succeed = False
    except:
        pass

    try:
        c_expr = parser.tree(query).toCode()
        eval(c_expr, rels)
        test_succeed = False
    except:
        pass

    if test_succeed:
        print (colorize('Test passed', COLOR_GREEN))
    else:
        print (colorize('Test failed (by not raising any exception)', COLOR_RED))
    return test_succeed
开发者ID:ltworf,项目名称:relational,代码行数:34,代码来源:driver.py


示例8: check_for_sdk_updates

def check_for_sdk_updates(auto_update_prompt=False):
    try:
        theirs = get_latest_version()
        yours = config.VERSION
    except LatestVersionCheckError:
        return
    if theirs <= yours:
        return
    url = 'https://github.com/grow/grow/releases/tag/{}'.format(theirs)
    logging.info('')
    logging.info('  Please update to the newest version of the Grow SDK.')
    logging.info('  See release notes: {}'.format(url))
    logging.info('  Your version: {}, latest version: {}'.format(
        colorize(yours, ansi=226), colorize(theirs, ansi=82)))
    if utils.is_packaged_app() and auto_update_prompt:
        # If the installation was successful, restart the process.
        try:
            if (raw_input('Auto update now? [y/N]: ').lower() == 'y'
                and subprocess.call(INSTALLER_COMMAND, shell=True) == 0):
                logging.info('Restarting...')
                os.execl(sys.argv[0], *sys.argv)
        except Exception as e:
            text = (
                'In-place update failed. Update manually or use:\n'
                '  curl https://install.growsdk.org | bash')
            logging.error(text)
            sys.exit(-1)
    else:
        logging.info('  Update using: ' + colorize('pip install --upgrade grow', ansi=200))
    print ''
开发者ID:hookerz,项目名称:grow,代码行数:30,代码来源:sdk_utils.py


示例9: colored_change

def colored_change(old, new, unit='', inverse=False):
    condition = old > new
    if inverse: condition = not condition
    if condition:
        return colorize(str(old) + unit, ansi=9) + ' -> ' + colorize(str(new) + unit, ansi=2)
    else:
        return colorize(str(old) + unit, ansi=2) + ' -> ' + colorize(str(new) + unit, ansi=9)
开发者ID:xtotdam,项目名称:steam-wishlist-diff,代码行数:7,代码来源:steam_wish_diff.py


示例10: compute_graph_matrix

    def compute_graph_matrix(self):
        """
        Compute and return contribution graph matrix

        """
        logger.debug("Printing graph")

        sorted_normalized_daily_contribution = sorted(self.daily_contribution_map)
        matrix = []
        first_day = sorted_normalized_daily_contribution[0]
        if first_day.strftime("%A") != "Sunday":
            c = self._Column(self.width)
            d = first_day - datetime.timedelta(days=1)
            while d.strftime("%A") != "Saturday":
                d = d - datetime.timedelta(days=1)
                c.append([None, self.width])
            matrix.append(c)
        else:
            new_column = self._Column(self.width)
            matrix.append(new_column)
        for current_day in sorted_normalized_daily_contribution:
            last_week_col = matrix[-1]
            day_contribution_color_index = int(self.daily_contribution_map[current_day])
            color = self.colors[day_contribution_color_index]

            try:
                last_week_col.append([current_day, colorize(self.width,
                                                            ansi=0,
                                                            ansi_bg=color)])

            except ValueError:  # column (e.g. week) has ended
                new_column = self._Column(self.width)
                matrix.append(new_column)
                last_week_col = matrix[-1]
                last_week_col.append([current_day, colorize(self.width,
                                                            ansi=0,
                                                            ansi_bg=color)])

            next_day = current_day + datetime.timedelta(days=1)
            if next_day.month != current_day.month:
                #  if the column we're at isn't 7 days yet, fill it with empty blocks
                last_week_col.fill()

                #  make new empty col to separate months
                matrix.append(self._Column(self.width, full_empty_col=True))

                matrix.append(self._Column(self.width))
                last_week_col = matrix[-1]  # update to the latest column

                #  if next_day (which is first day of new month) starts in middle of the
                #  week, prepend empty blocks in the column before inserting 'next day'
                next_day_num = DAYS.index(next_day.strftime("%A"))
                last_week_col.fill_by(next_day_num)

        # make sure that the most current week (last col of matrix) col is of size 7,
        #  so fill it if it's not
        matrix[-1].fill()

        return matrix
开发者ID:AmmsA,项目名称:Githeat,代码行数:59,代码来源:githeat.py


示例11: start

def start(pod, host=None, port=None, open_browser=False, debug=False,
          preprocess=True):
  observer, podspec_observer = file_watchers.create_dev_server_observers(pod)
  if preprocess:
    # Run preprocessors for the first time in a thread.
    thread = threading.Thread(target=pod.preprocess)
    thread.start()

  try:
    # Create the development server.
    app = main_lib.CreateWSGIApplication(pod)
    port = 8080 if port is None else int(port)
    host = 'localhost' if host is None else host
    num_tries = 0
    while num_tries < 10:
      try:
        httpd = simple_server.make_server(host, port, app,
                                          handler_class=DevServerWSGIRequestHandler)
        num_tries = 99
      except socket.error as e:
        if e.errno == 48:
          num_tries += 1
          port += 1
        else:
          raise e

  except Exception as e:
    logging.error('Failed to start server: {}'.format(e))
    observer.stop()
    observer.join()
    sys.exit()

  try:
    root_path = pod.get_root_path()
    url = 'http://{}:{}{}'.format(host, port, root_path)
    print 'Pod: '.rjust(20) + pod.root
    print 'Address: '.rjust(20) + url
    print colorize('Server ready. '.rjust(20), ansi=47) + 'Press ctrl-c to quit.'
    def start_browser(server_ready_event):
      server_ready_event.wait()
      if open_browser:
        webbrowser.open(url)
    server_ready_event = threading.Event()
    browser_thread = threading.Thread(target=start_browser,
                                      args=(server_ready_event,))
    browser_thread.start()
    server_ready_event.set()
    httpd.serve_forever()
    browser_thread.join()

  except KeyboardInterrupt:
    logging.info('Goodbye. Shutting down.')
    httpd.server_close()
    observer.stop()
    observer.join()

  # Clean up once server exits.
  sys.exit()
开发者ID:meizon,项目名称:pygrow,代码行数:58,代码来源:manager.py


示例12: generate_list

def generate_list():
    """ Prints listing of all the available licenses.
    """

    print colorize("Lisense currently supports %d licenses.\n" %
                   (len(catalogue)),
                   ansi=4)

    for label, license in catalogue.iteritems():
        print colorize("- %s" % (license), ansi=253)
开发者ID:pravj,项目名称:lisense,代码行数:10,代码来源:list.py


示例13: print_server_ready_message

def print_server_ready_message(pod, host, port):
  home_doc = pod.get_home_doc()
  if home_doc:
    root_path = home_doc.url.path
  else:
    root_path = pod.get_root_path()
  url = 'http://{}:{}{}'.format(host, port, root_path)
  print 'Pod: '.rjust(20) + pod.root
  print 'Address: '.rjust(20) + url
  print colorize('Server ready. '.rjust(20), ansi=47) + 'Press ctrl-c to quit.'
  return url
开发者ID:stucox,项目名称:pygrow,代码行数:11,代码来源:manager.py


示例14: log_request

 def log_request(self, code=0, size='-'):
   if not self._logging_enabled:
     return
   line = self.requestline[:-9]
   method, line = line.split(' ', 1)
   color = 19
   if int(code) >= 500:
     color = 161
   code = colorize(code, ansi=color)
   size = colorize(DevServerWSGIRequestHandler.sizeof(size), ansi=19)
   self.log_message('{} {} {}'.format(code, line, size))
开发者ID:jasonsemko,项目名称:pygrow,代码行数:11,代码来源:manager.py


示例15: machine_translate

def machine_translate(pod_path, locale):
  """Translates the pod message catalog using machine translation."""
  root = os.path.abspath(os.path.join(os.getcwd(), pod_path))
  pod = pods.Pod(root, storage=storage.FileStorage)
  pod.catalogs.extract()
  for locale in locale:
    catalog = pod.catalogs.get(locale)
    catalog.update()
    catalog.machine_translate()
  print colorize('WARNING! Use machine translations with caution.', ansi=197)
  print colorize('Machine translations are not intended for use in production.', ansi=197)
开发者ID:jasonsemko,项目名称:pygrow,代码行数:11,代码来源:machine_translate.py


示例16: map

    def map(h2: 'Histogram2D', **kwargs):
        """Heat map.

        Note: Available only if xtermcolor present.
        """

        # Value format
        val_format = kwargs.pop("value_format", ".2f")         
        if isinstance(val_format, str):
            value_format = lambda val: (("{0:" + val_format + "}").format(val))
        
        data = (h2.frequencies / h2.frequencies.max() * 255).astype(int)
        
        # Colour map
        cmap = kwargs.pop("cmap", DEFAULT_CMAP)
        if cmap == "Greys":
            data = 255 - data
            colorbar_range = range(h2.shape[1] + 1, -1, -1)
        elif cmap == "Greys_r":
            colorbar_range = range(h2.shape[1] + 2)
        else:
            raise ValueError("Unsupported colormap: {0}, select from: {1}".format(cmap, SUPPORTED_CMAPS))
        colors = (65536 + 256 + 1) * data

        print((value_format(h2.get_bin_right_edges(0)[-1]) + " →").rjust(h2.shape[1] + 2, " "))
        print("+" + "-" * h2.shape[1] + "+")
        for i in range(h2.shape[0]-1, -1, -1):
            line = [
                xtermcolor.colorize("█", bg=0, rgb=colors[i,j])
                for j in range(h2.shape[1])
            ]
            line = "|" + "".join(line) + "|"
            if i == h2.shape[0]-1:
                line += value_format(h2.get_bin_right_edges(1)[-1]) + " ↑"
            if i == 0:
                line += value_format(h2.get_bin_left_edges(1)[0]) + " ↓"
            print(line)
        print("+" + "-" * h2.shape[1] + "+")
        print("←", value_format(h2.get_bin_left_edges(0)[0]))
        colorbar = [
            xtermcolor.colorize("█", bg=0, rgb=(65536 + 256 + 1) * int(j * 255 / (h2.shape[1] + 2)))
            for j in colorbar_range
            ]
        colorbar = "".join(colorbar)
        print()
        print("↓", 0)
        print(colorbar)
        print(str(h2.frequencies.max()).rjust(h2.shape[1], " "), "↑")
开发者ID:janpipek,项目名称:physt,代码行数:48,代码来源:ascii.py


示例17: getName

 def getName(self,color=False):
     '''Returns a nice version of the name
     If color is true, then 256-color escapes will be
     added to give the name the color of the line'''
     name = self.name
     name = name.replace(u'Spårvagn','')
     name = name.replace(u'Buss','')
     name += " "
     
     if self.direction !=None:
         name+=self.direction+ " "
     
     if self.wheelchair:
         name += u"♿ "
     if self.night:
         name += u"☾ "
     
     while len(name)<20:
         name=" "+name
     
     if not color:
         return name
 
     bgcolor = int('0x' + self.fgcolor[1:],16)
     fgcolor = int('0x' + self.bgcolor[1:],16)
     return colorize(name.encode('utf8'),fgcolor,bg=bgcolor).decode('utf8')
开发者ID:kchr,项目名称:pysttrafik,代码行数:26,代码来源:pysttrafik.py


示例18: print_total

 def print_total(self):
     colors = {}
     for i, person in enumerate(sorted(list(self.people))):
         colors[person] = i+1
     for (p1, p2), value in self.graph.iteritems():
         if value > 0:
             creditor, debitor = p1, p2
         elif value < 0:
             value *= -1
             creditor, debitor = p2, p1
         else:
             continue
         debitor = colorize(debitor, ansi=colors[debitor])
         creditor = colorize(creditor, ansi=colors[creditor])
         print("{} owes {} {}".format(debitor, creditor, value))
     print("")
开发者ID:themiurgo,项目名称:billclin,代码行数:16,代码来源:billclin.py


示例19: dbg_format_exception_msg

    def dbg_format_exception_msg(self, profile, extype, msg, tb):
        
        # override message format if configured
        if 'format' in profile:
            msg_format = profile['format']
        else:
            msg_format = "[{timestamp}] EXCEPTION:[{thrid}): {msg}\n{trace}"
                
        thrid = '0' if multiprocessing.current_process().name == 'MainProcess' else multiprocessing.current_process().name
        now = datetime.now()
        now_ms = "{:.3f}".format(round(int(now.strftime("%f")).__float__() / 1000000, 3))
        now_ms = now_ms.split('.')[1]
        tb_lines = traceback.format_list(traceback.extract_tb(tb))
        trace = ''
        for tb_line in tb_lines:
            trace += "\t{0}".format(tb_line)
            
        format_options = {
           'timestamp' : now.strftime("%d/%m/%Y %H:%M:%S,{0}".format(now_ms)),
           'shorttime' : now.strftime("%H:%M:%S.{0}".format(now_ms)),        
            'thrid'    : thrid,
            'msg'      : msg,
            'extype'   : extype.__name__,
            'trace'    : trace 
        }
        format_options.update(self._dbg_msg_format_vars)            
        msg_text = msg_format.format(**format_options)

        # override message color if configured
        if 'term_color' in profile and profile['term_color'] is not None and '#' == profile['term_color'][0]:
            rgb_color = profile['term_color'].replace('#', '')
            msg_text = colorize(msg_text, int(rgb_color, 16))
        
                
        return msg_text
开发者ID:hydratk,项目名称:hydratk,代码行数:35,代码来源:debugger.py


示例20: dbg_format_msg

    def dbg_format_msg(self, profile, msg, location={'file': None, 'line': None, 'module': None, 'func': None, 'call_path': None, 'class' : None }, level=1, channel=[]):
        """Method implements message formating

        Args:     
           profile (dict)  : logger dictionary profile
           msg (string)    : message
           location (dict) : message trace parameters
           level (int)     : debug level
           channel (list)  : channel filter list

        Returns:
           bool: result

        """                  
        msg_text = False
        process_msg = False 
        
        if profile['log_type'] == 'debug':
            debug_level = self._debug_level if self._debug_level is not None else profile['level']
            debug_channel = self._debug_channel if len(self._debug_channel) > 0 else profile['channel']
            if (debug_level >= level and self.match_channel(channel, debug_channel) == True):
                process_msg = True
        else:
            process_msg = True
        
        if process_msg == True:
            thrid = '0' if multiprocessing.current_process().name == 'MainProcess' else multiprocessing.current_process().name
            

            # override message format if configured
            if 'format' in profile:
                msg_format = profile['format']
            else:
                msg_format = '[{timestamp}] DEBUG({level}): {callpath}:{func}:{thrid}: {msg}{lf}'
           
            now = datetime.now()
            now_ms = "{:.3f}".format(round(int(now.strftime("%f")).__float__() / 1000000, 3))
            now_ms = now_ms.split('.')[1]
            format_options = {
               'timestamp' : now.strftime("%d/%m/%Y %H:%M:%S,{0}".format(now_ms)),
               'shorttime' : now.strftime("%H:%M:%S.{0}".format(now_ms)),
               'level'     : level,
                'file'     : location['file'],
                'line'     : location['line'],
                'module'   : location['module'],
                'callpath' : location['call_path'],
                'func'     : "{0}.{1}".format(location['class'],location['func']) if location['class'] != None else location['func'],
                'thrid'    : thrid,
                'msg'      : msg,
                'channel'  : channel,
            }
            format_options.update(self._dbg_msg_format_vars)            
            msg_text = msg_format.format(**format_options)

            # override message color if configured
            if 'term_color' in profile and profile['term_color'] is not None and '#' == profile['term_color'][0]:
                rgb_color = profile['term_color'].replace('#', '')
                msg_text = colorize(msg_text, int(rgb_color, 16))

        return msg_text            
开发者ID:hydratk,项目名称:hydratk,代码行数:60,代码来源:debugger.py



注:本文中的xtermcolor.colorize函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python xtuml.one函数代码示例发布时间:2022-05-26
下一篇:
Python xstruct.pack函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap