Python colorclass.Color() Examples
The following are 30
code examples of colorclass.Color().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
colorclass
, or try the search function
.
Example #1
Source File: test_regression.py From python-tabulate with MIT License | 6 votes |
def test_colorclass_colors(): "Regression: ANSI colors in a unicode/str subclass (issue #49)" try: import colorclass s = colorclass.Color("{magenta}3.14{/magenta}") result = tabulate([[s]], tablefmt="plain") expected = "\x1b[35m3.14\x1b[39m" assert_equal(result, expected) except ImportError: class textclass(_text_type): pass s = textclass("\x1b[35m3.14\x1b[39m") result = tabulate([[s]], tablefmt="plain") expected = "\x1b[35m3.14\x1b[39m" assert_equal(result, expected)
Example #2
Source File: test_max_dimensions.py From terminaltables with MIT License | 6 votes |
def test_colors_cjk_rtl(): """Test color text, CJK characters, and RTL characters.""" table_data = [ [Color('{blue}Test{/blue}')], [Fore.BLUE + 'Test' + Fore.RESET], [colored('Test', 'blue')], ] assert max_dimensions(table_data) == ([4], [1, 1, 1], [4], [1, 1, 1]) table_data = [ ['蓝色'], ['世界你好'], ] assert max_dimensions(table_data) == ([8], [1, 1], [8], [1, 1]) table_data = [ ['שלום'], ['معرب'], ] assert max_dimensions(table_data) == ([4], [1, 1], [4], [1, 1])
Example #3
Source File: cricket_calender.py From Scripting-and-Web-Scraping with MIT License | 6 votes |
def main(): choice=menu() if(choice==1) : team=input("\n Enter team's name:") while(len(team)<=1): print(Color('{autored}\n Enter valid team name{/autored}')) team=input("\n Enter team's name:") make_table(team) else: team1=input("\n Enter name of team 1:") team2=input(" Enter name of team 2:") while(len(team1)<=1 or len(team2)<=1 or team1.strip(' ')==team2.strip(' ')): print(Color('{autored}\n Enter valid team names{/autored}')) team1=input("\n Enter name of team 1:") team2=input(" Enter name of team 2:") make_table(team1,team2)
Example #4
Source File: test_table.py From terminaltables with MIT License | 6 votes |
def test_color(): """Test with color characters.""" table_data = [ ['ansi', '\033[31mRed\033[39m', '\033[32mGreen\033[39m', '\033[34mBlue\033[39m'], ['colorclass', Color('{red}Red{/red}'), Color('{green}Green{/green}'), Color('{blue}Blue{/blue}')], ['colorama', Fore.RED + 'Red' + Fore.RESET, Fore.GREEN + 'Green' + Fore.RESET, Fore.BLUE + 'Blue' + Fore.RESET], ['termcolor', colored('Red', 'red'), colored('Green', 'green'), colored('Blue', 'blue')], ] table = BaseTable(table_data) table.inner_heading_row_border = False actual = table.table expected = ( u'+------------+-----+-------+------+\n' u'| ansi | \033[31mRed\033[39m | \033[32mGreen\033[39m | \033[34mBlue\033[39m |\n' u'| colorclass | \033[31mRed\033[39m | \033[32mGreen\033[39m | \033[34mBlue\033[39m |\n' u'| colorama | \033[31mRed\033[39m | \033[32mGreen\033[39m | \033[34mBlue\033[39m |\n' u'| termcolor | \033[31mRed\033[0m | \033[32mGreen\033[0m | \033[34mBlue\033[0m |\n' u'+------------+-----+-------+------+' ) assert actual == expected
Example #5
Source File: tables.py From python-libmaas with GNU Affero General Public License v3.0 | 6 votes |
def render(self, target, vlan): if vlan.dhcp_on: if vlan.primary_rack: if vlan.secondary_rack: text = "HA Enabled" else: text = "Enabled" if target == RenderTarget.pretty: text = Color("{autogreen}%s{/autogreen}") % text elif vlan.relay_vlan: text = "Relayed via %s.%s" % (vlan.fabric.name, vlan.vid) if target == RenderTarget.pretty: text = Color("{autoblue}%s{/autoblue}") % text else: text = "Disabled" return super().render(target, text)
Example #6
Source File: test_table.py From terminaltables with MIT License | 6 votes |
def test_ascii(): """Test with ASCII characters.""" table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ] table = BaseTable(table_data) actual = table.table expected = ( '+---------+-------+-----------+\n' '| Name | Color | Type |\n' '+---------+-------+-----------+\n' '| Avocado | green | nut |\n' '| Tomato | red | fruit |\n' '| Lettuce | green | vegetable |\n' '+---------+-------+-----------+' ) assert actual == expected
Example #7
Source File: example2.py From terminaltables with MIT License | 5 votes |
def table_server_timings(): """Return table string to be printed.""" table_data = [ [Color('{autogreen}<10ms{/autogreen}'), '192.168.0.100, 192.168.0.101'], [Color('{autoyellow}10ms <= 100ms{/autoyellow}'), '192.168.0.102, 192.168.0.103'], [Color('{autored}>100ms{/autored}'), '192.168.0.105'], ] table_instance = SingleTable(table_data) table_instance.inner_heading_row_border = False return table_instance.table
Example #8
Source File: packages_status_detector.py From pip-upgrader with Apache License 2.0 | 5 votes |
def _update_index_url_from_configs(self): """ Checks for alternative index-url in pip.conf """ if 'VIRTUAL_ENV' in os.environ: self.pip_config_locations.append(os.path.join(os.environ['VIRTUAL_ENV'], 'pip.conf')) self.pip_config_locations.append(os.path.join(os.environ['VIRTUAL_ENV'], 'pip.ini')) if site_config_files: self.pip_config_locations.extend(site_config_files) index_url = None custom_config = None if 'PIP_INDEX_URL' in os.environ and os.environ['PIP_INDEX_URL']: # environ variable takes priority index_url = os.environ['PIP_INDEX_URL'] custom_config = 'PIP_INDEX_URL environment variable' else: for pip_config_filename in self.pip_config_locations: if pip_config_filename.startswith('~'): pip_config_filename = os.path.expanduser(pip_config_filename) if os.path.isfile(pip_config_filename): config = ConfigParser() config.read([pip_config_filename]) try: index_url = config.get('global', 'index-url') custom_config = pip_config_filename break # stop on first detected, because config locations have a priority except (NoOptionError, NoSectionError): # pragma: nocover pass if index_url: self.PYPI_API_URL = self._prepare_api_url(index_url) print(Color('Setting API url to {{autoyellow}}{}{{/autoyellow}} as found in {{autoyellow}}{}{{/autoyellow}}' '. Use --default-index-url to use pypi default index'.format(self.PYPI_API_URL, custom_config)))
Example #9
Source File: cmdline_printer.py From homer with MIT License | 5 votes |
def print_article_stats(self): """This method is called to present overall article stats on a command line.""" table_data = [ [Color('{autocyan}Overall Stats{/autocyan}')], ['Reading time', str(self.article.reading_time) + ' mins'], ['Flesch Reading Ease', self.article.get_flesch_reading_score()], ['Dale Chall Readability Score', self.article.get_dale_chall_reading_score()], ['Paragraphs', self.article.total_paragraphs], ['Avg sentences per paragraph', self.article.avg_sentences_per_para], ['Total sentences in longest paragraph', self.article.len_of_longest_paragraph], ['Sentences', self.article.total_sentences], ['Avg words per sentence', self.article.avg_words_per_sentence], ['Longest sentence', "%s..." % str(self.article.longest_sentence)[0:30]], ['Words in longest sentence', self.article.len_of_longest_sentence], ['Words', self.article.total_words], ['"and" frequency"', self.article.get_and_frequency()], ['Compulsive Hedgers', len(self.article.get_compulsive_hedgers())], ['Intensifiers', len(self.article.get_intensifiers())], ['Vague words', len(self.article.get_vague_words())], ] table_instance = SingleTable(table_data) table_instance.inner_heading_row_border = True table_instance.inner_row_border = True table_instance.justify_columns = {0: 'left', 1: 'center'} print(table_instance.table) self.print_detail()
Example #10
Source File: cmdline_printer.py From homer with MIT License | 5 votes |
def print_paragraph_stats(self): """This method, along with print_article_stats(), can be called to present paragraph stats on a command line. Ideally first call print_article_stats() and then this method. It shows sentence, average words per sentence, longest sentence, and readability scores (Flesch reading ease and Dale Chall readability scores) of paragraphs. """ sentence_tag = Color('{blue}sentences{/blue}') word_tag = Color('{blue}words{/blue}') avg_word_tag = Color('{blue}Avg words per sentence{/blue}') long_tag = Color('{red}longest{/red}') table_data = [ [Color('{autocyan}Paragraph Stats{/autocyan}')], ['Paragraph #', ''] ] for item, para in enumerate(self.article.paragraphs): sentences = Color('{red}%s{/red}' % str(len(para))) if len(para) > 5 else str(len(para)) avg_words_per_sentence = Color( '{red}%s{/red}' % str(para.avg_words_per_sentence)) if para.avg_words_per_sentence > 25 else str( para.avg_words_per_sentence) table_data.append([item + 1, '{sentences} {sent_tag}. {words} {word_tag}. {avg_words} {avg_word_tag}. ' '"{longest_sent}..." is the {long_tag} sentence.'.format( sentences=sentences, sent_tag=sentence_tag, words=para.total_words, word_tag=word_tag, avg_words=avg_words_per_sentence, avg_word_tag=avg_word_tag, longest_sent=str(para.longest_sentence)[0:10], long_tag=long_tag )]) table_data.append(["", "Flesh Reading score={flesch_reading}, Dale Chall Readability= {dale_chall}".format( flesch_reading=para.get_flesch_reading_score(), dale_chall=para.get_dale_chall_reading_score() )]) table_instance = SingleTable(table_data) table_instance.inner_heading_row_border = True table_instance.inner_row_border = True table_instance.justify_columns = {0: 'center', 1: 'left'} print(table_instance.table)
Example #11
Source File: cmdline_printer.py From homer with MIT License | 5 votes |
def _print_detail_of(self, words_list, heading, display_count=True): words = [str(word) for word in words_list] if len(words) >= 1: words_unique_list = list(set(words)) format_str = "{word} ({count})" if display_count: msg = '{red} **- %s: %s {/red}\r\n' % (heading, ', '.join(format_str.format(word=str(word), count=words.count(word)) for word in words_unique_list)) else: msg = '{red} **- %s: %s {/red}\r\n' % (heading, ', '.join(word for word in words_unique_list)) print(Color(msg))
Example #12
Source File: shell.py From RobinhoodShell with MIT License | 5 votes |
def color_data(value): if float(value) > 0: number = Color('{autogreen}'+str(value)+'{/autogreen}') elif float(value) < 0: number = Color('{autored}'+str(value)+'{/autored}') else: number = str(value) return number
Example #13
Source File: __init__.py From python-libmaas with GNU Affero General Public License v3.0 | 5 votes |
def colorized(text): if sys.stdout.isatty(): # Don't return value_colors; returning the Color instance allows # terminaltables to correctly calculate alignment and padding. return colorclass.Color(text) else: return colorclass.Color(text).value_no_colors
Example #14
Source File: tables.py From python-libmaas with GNU Affero General Public License v3.0 | 5 votes |
def render(self, target, datum): if target == RenderTarget.pretty: if datum in self.colours: colour = self.colours[datum] return Color("{%s}%s{/%s}" % (colour, datum, colour)) else: return datum else: return super().render(target, datum)
Example #15
Source File: tables.py From python-libmaas with GNU Affero General Public License v3.0 | 5 votes |
def render(self, target, data): if target == RenderTarget.pretty: if data in self.colours: colour = self.colours[data] return Color("{%s}%s{/%s}" % (colour, data.value.capitalize(), colour)) else: return data.value.capitalize() elif target == RenderTarget.plain: return super().render(target, data.value.capitalize()) else: return super().render(target, data.value)
Example #16
Source File: tables.py From python-libmaas with GNU Affero General Public License v3.0 | 5 votes |
def render(self, target, active): if active: text = "Active" else: text = "Disabled" if target == RenderTarget.pretty and active: text = Color("{autogreen}Active{/autogreen}") return super().render(target, text)
Example #17
Source File: tabular.py From python-libmaas with GNU Affero General Public License v3.0 | 5 votes |
def render(self, target, datum): if target is RenderTarget.yaml: return datum elif target is RenderTarget.json: return datum elif target is RenderTarget.csv: if isinstance(datum, collections.Iterable) and not isinstance( datum, (str, bytes) ): return ",".join(datum) else: return datum elif target is RenderTarget.plain: if datum is None: return "" elif isinstance(datum, colorclass.Color): return datum.value_no_colors elif isinstance(datum, collections.Iterable) and not isinstance( datum, (str, bytes) ): return "\n".join(datum) else: return str(datum) elif target is RenderTarget.pretty: if datum is None: return "" elif isinstance(datum, colorclass.Color): return datum elif isinstance(datum, collections.Iterable) and not isinstance( datum, (str, bytes) ): return "\n".join(datum) else: return str(datum) else: raise ValueError("Cannot render %r for %s" % (datum, target))
Example #18
Source File: response.py From linode-cli with BSD 3-Clause "New" or "Revised" License | 5 votes |
def render_value(self, model, colorize=True): """ Given the model returned from the API, returns the correctly- rendered version of it. This can transform text based on various rules configured in the spec using custom tags. Currently supported tags: x-linode-cli-color A list of key-value pairs that represent the value, and its ideal color. The key "default_" is used to colorize anything that is not included. If omitted, no color is applied. """ value = self._get_value(model) if isinstance(value, list): value = ', '.join([str(c) for c in value]) if colorize and self.color_map is not None: # apply colors value = str(value) # just in case color = self.color_map.get(value) or self.color_map['default_'] value = str(Color('{'+color+'}'+value+'{/'+color+'}')) if value is None: # don't print the word "None" value = '' return value
Example #19
Source File: virtualenv_checker.py From pip-upgrader with Apache License 2.0 | 5 votes |
def check_for_virtualenv(options): if options.get('--skip-virtualenv-check', False) or options.get('--skip-package-installation', False): return # no check needed if not is_virtualenv(): print(Color("{autoyellow}It seems you haven't activated a virtualenv. \n" "Installing packages directly in the system is not recommended. \n" "{automagenta}Activate your project's virtualenv{/automagenta}, " "or {automagenta}re-run this command {/automagenta}with one of the following options:\n" "--skip-virtualenv-check (install the packages anyway)\n" "--skip-package-installation (don't install any package. just update the requirements file(s))" "{/autoyellow}")) raise KeyboardInterrupt()
Example #20
Source File: packages_interactive_selector.py From pip-upgrader with Apache License 2.0 | 5 votes |
def __init__(self, packages_map, options): self.selected_packages = [] self.packages_for_upgrade = {} # map with index number, for later choosing i = 1 for package in packages_map.values(): if package['upgrade_available']: self.packages_for_upgrade[i] = package.copy() i += 1 # maybe all packages are up-to-date if not self.packages_for_upgrade: print(Color('{autogreen}All packages are up-to-date.{/autogreen}')) raise KeyboardInterrupt() # choose which packages to upgrade (interactive or not) if '-p' in options and options['-p']: if options['-p'] == ['all']: self._select_packages(self.packages_for_upgrade.keys()) else: for index, package in self.packages_for_upgrade.items(): for chosen_package in options['-p']: if chosen_package.lower().strip() == package['name'].lower().strip(): self._select_packages([index]) else: self.ask_for_packages()
Example #21
Source File: cli.py From pip-upgrader with Apache License 2.0 | 5 votes |
def main(): """ Main CLI entrypoint. """ options = get_options() Windows.enable(auto_colors=True, reset_atexit=True) try: # maybe check if virtualenv is not activated check_for_virtualenv(options) # 1. detect requirements files filenames = RequirementsDetector(options.get('<requirements_file>')).get_filenames() if filenames: print(Color('{{autoyellow}}Found valid requirements file(s):{{/autoyellow}} ' '{{autocyan}}\n{}{{/autocyan}}'.format('\n'.join(filenames)))) else: # pragma: nocover print(Color('{autoyellow}No requirements files found in current directory. CD into your project ' 'or manually specify requirements files as arguments.{/autoyellow}')) return # 2. detect all packages inside requirements packages = PackagesDetector(filenames).get_packages() # 3. query pypi API, see which package has a newer version vs the one in requirements (or current env) packages_status_map = PackagesStatusDetector( packages, options.get('--use-default-index')).detect_available_upgrades(options) # 4. [optionally], show interactive screen when user can choose which packages to upgrade selected_packages = PackageInteractiveSelector(packages_status_map, options).get_packages() # 5. having the list of packages, do the actual upgrade and replace the version inside all filenames upgraded_packages = PackagesUpgrader(selected_packages, filenames, options).do_upgrade() print(Color('{{autogreen}}Successfully upgraded (and updated requirements) for the following packages: ' '{}{{/autogreen}}'.format(','.join([package['name'] for package in upgraded_packages])))) if options['--dry-run']: print(Color('{automagenta}Actually, no, because this was a simulation using --dry-run{/automagenta}')) except KeyboardInterrupt: # pragma: nocover print(Color('\n{autored}Upgrade interrupted.{/autored}'))
Example #22
Source File: test_ascii_table.py From terminaltables with MIT License | 5 votes |
def test_single_line(): """Test single-lined cells.""" table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ['Watermelon', 'green'], [], ] table = AsciiTable(table_data, 'Example') table.inner_footing_row_border = True table.justify_columns[0] = 'left' table.justify_columns[1] = 'center' table.justify_columns[2] = 'right' actual = table.table expected = ( '+Example-----+-------+-----------+\n' '| Name | Color | Type |\n' '+------------+-------+-----------+\n' '| Avocado | green | nut |\n' '| Tomato | red | fruit |\n' '| Lettuce | green | vegetable |\n' '| Watermelon | green | |\n' '+------------+-------+-----------+\n' '| | | |\n' '+------------+-------+-----------+' ) assert actual == expected
Example #23
Source File: runner.py From aws-service-catalog-puppet with Apache License 2.0 | 5 votes |
def run_tasks_for_bootstrap_spokes_in_ou(tasks_to_run, num_workers): for type in ["failure", "success", "timeout", "process_failure", "processing_time", "broken_task", ]: os.makedirs(Path(constants.RESULTS_DIRECTORY) / type) run_result = luigi.build( tasks_to_run, local_scheduler=True, detailed_summary=True, workers=num_workers, log_level='INFO', ) for filename in glob('results/failure/*.json'): result = json.loads(open(filename, 'r').read()) click.echo(colorclass.Color("{red}" + result.get('task_type') + " failed{/red}")) click.echo(f"{yaml.safe_dump({'parameters':result.get('task_params')})}") click.echo("\n".join(result.get('exception_stack_trace'))) click.echo('') exit_status_codes = { LuigiStatusCode.SUCCESS: 0, LuigiStatusCode.SUCCESS_WITH_RETRY: 0, LuigiStatusCode.FAILED: 1, LuigiStatusCode.FAILED_AND_SCHEDULING_FAILED: 2, LuigiStatusCode.SCHEDULING_FAILED: 3, LuigiStatusCode.NOT_RUN: 4, LuigiStatusCode.MISSING_EXT: 5, } sys.exit(exit_status_codes.get(run_result.status))
Example #24
Source File: hinton.py From inferbeddings with MIT License | 5 votes |
def _hinton_diagram_value(val, max_val): chars = [' ', '▁', '▂', '▃', '▄', '▅'] #, '▆', '▇', '█'] # chars = [' ', '·', '▪', '■', '█'] step = len(chars) - 1 if abs(abs(val) - max_val) >= 1e-8: step = int(abs(float(val) / max_val) * len(chars)) attr = 'red' if val < 0 else 'green' return Color('{auto' + attr + '}' + str(chars[step]) + '{/auto' + attr + '}')
Example #25
Source File: charts.py From Scripting-and-Web-Scraping with MIT License | 5 votes |
def make_table(result): table_data = [['S.No', 'Name', 'Rating']] for s_no,res in enumerate(result,1): row = [] row.extend((Color('{autoyellow}' + str(s_no) + '.' + '{/autoyellow}'), Color('{autogreen}' + res[0] + '{/autogreen}'), Color('{autoyellow}' + res[1] + '{/autoyellow}'))) table_data.append(row) table_instance = DoubleTable(table_data) table_instance.inner_row_border = True print(table_instance.table) print()
Example #26
Source File: cricket_calender.py From Scripting-and-Web-Scraping with MIT License | 5 votes |
def make_table(team1,team2=''): data=scrape() table_data=[['Match','Series','Date','Month','Time']] for i in data[:]: row=[] if team1.strip(' ') in i.get('desc') and team2.strip(' ') in i.get('desc') : row.extend((Color('{autoyellow}'+i.get('desc')+'{/autoyellow}'),Color('{autocyan}'+i.get('srs')[5:]+'{/autocyan}'),Color('{autored}'+i.get('ddt')+'{/autored}'),Color('{autogreen}'+i.get('mnth_yr')+'{/autogreen}'),Color('{autoyellow}'+i.get('tm')+'{/autoyellow}'))) table_data.append(row) table_instance = DoubleTable(table_data) table_instance.inner_row_border = True print(table_instance.table) print()
Example #27
Source File: test_max_dimensions.py From terminaltables with MIT License | 5 votes |
def test_single_line(): """Test widths.""" table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ] assert max_dimensions(table_data, 1, 1) == ([7, 5, 9], [1, 1, 1, 1], [9, 7, 11], [1, 1, 1, 1]) table_data.append(['Watermelon', 'green', 'fruit']) assert max_dimensions(table_data, 2, 2) == ([10, 5, 9], [1, 1, 1, 1, 1], [14, 9, 13], [1, 1, 1, 1, 1])
Example #28
Source File: cricket_calender.py From Scripting-and-Web-Scraping with MIT License | 5 votes |
def menu(): print(' Search by team') print(' 1.One team: ') print(' 2.Two teams: ') choice=input('\n Enter your choice:') while(choice not in ['1','2']): print(Color('{autored}\n Wrong choice{/autored}')) choice=input('\n Enter your choice:') teams=['Ind','SL','Aus','Ban','RSA','ZIM','NZ','Eng','WI'] print() print(teams) return int(choice)
Example #29
Source File: status.py From provisionpad with Apache License 2.0 | 5 votes |
def stat(self, DB): """Return table string to be printed.""" table_data = [[Color('{'+self.color+'}Name{/'+self.color+'}'), 'Type', 'Volumes', 'SSH']] for ins, ins_val in DB[self.instance_status].items(): volume = 'root;' for _, val in ins_val['sdrive'].items(): volume += ' {0} GB;'.format(val['size']) table_data.append([Color('{'+self.color+'}'+ins+'{/'+self.color+'}'), ins_val['type'], volume,'ssh {0}'.format(ins)]) table_instance = SingleTable(table_data, self.instance_status) table_instance.inner_heading_row_border = True return table_instance.table
Example #30
Source File: output.py From Interlace with GNU General Public License v3.0 | 5 votes |
def terminal(self, level, target, command, message=""): if level == 0 and not self.verbose: return formatting = { 0: Color('{autoblue}[VERBOSE]{/autoblue}'), 1: Color('{autogreen}[THREAD]{/autogreen}'), 3: Color('{autobgyellow}{autored}[ERROR]{/autored}{/autobgyellow}') } leader = formatting.get(level, '[#]') format_args = { 'time': strftime("%H:%M:%S", localtime()), 'target': target, 'command': command, 'message': message, 'leader': leader } if not self.silent: if level == 1: template = '[{time}] {leader} [{target}] {command} {message}' else: template = '[{time}] {leader} [{target}] {command} {message}' print(template.format(**format_args))