Python colorama.Fore.BLACK Examples
The following are 30
code examples of colorama.Fore.BLACK().
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
colorama.Fore
, or try the search function
.
Example #1
Source File: log.py From odoo-module-migrator with GNU Affero General Public License v3.0 | 6 votes |
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)
Example #2
Source File: _grep.py From nbcommands with Apache License 2.0 | 6 votes |
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
Example #3
Source File: munin-host.py From munin with Apache License 2.0 | 6 votes |
def print_highlighted(line, hl_color=Back.WHITE): """ Print a highlighted line """ try: # Highlight positives colorer = re.compile(r'([^\s]+) POSITIVES: ([1-9]) ') line = colorer.sub(Fore.YELLOW + r'\1 ' + 'POSITIVES: ' + Fore.YELLOW + r'\2 ' + Style.RESET_ALL, line) colorer = re.compile(r'([^\s]+) POSITIVES: ([0-9]+) ') line = colorer.sub(Fore.RED + r'\1 ' + 'POSITIVES: ' + Fore.RED + r'\2 ' + Style.RESET_ALL, line) # Keyword highlight colorer = re.compile(r'([A-Z_]{2,}:)\s', re.VERBOSE) line = colorer.sub(Fore.BLACK + hl_color + r'\1' + Style.RESET_ALL + ' ', line) print(line) except Exception as e: pass
Example #4
Source File: munin_stdout.py From munin with Apache License 2.0 | 6 votes |
def printHighlighted(line, hl_color=Back.WHITE, tag_color=False): """ Print a highlighted line """ if tag_color: # Tags colorer = re.compile('(HARMLESS|SIGNED|MS_SOFTWARE_CATALOGUE|MSSOFT|SUCCESSFULLY\sCOMMENTED)', re.VERBOSE) line = colorer.sub(Fore.BLACK + Back.GREEN + r'\1' + Style.RESET_ALL + '', line) colorer = re.compile('(REVOKED|EXPLOIT|CVE-[0-9\-]+|OBFUSCATED|RUN\-FILE)', re.VERBOSE) line = colorer.sub(Fore.BLACK + Back.RED + r'\1' + Style.RESET_ALL + '', line) colorer = re.compile('(EXPIRED|VIA\-TOR|OLE\-EMBEDDED|RTF|ATTACHMENT|ASPACK|UPX|AUTO\-OPEN|MACROS)', re.VERBOSE) line = colorer.sub(Fore.BLACK + Back.YELLOW + r'\1' + Style.RESET_ALL + '', line) # Extras colorer = re.compile('(\[!\])', re.VERBOSE) line = colorer.sub(Fore.BLACK + Back.LIGHTMAGENTA_EX + r'\1' + Style.RESET_ALL + '', line) # Add line breaks colorer = re.compile('(ORIGNAME:)', re.VERBOSE) line = colorer.sub(r'\n\1', line) # Standard colorer = re.compile('([A-Z_]{2,}:)\s', re.VERBOSE) line = colorer.sub(Fore.BLACK + hl_color + r'\1' + Style.RESET_ALL + ' ', line) print(line)
Example #5
Source File: vt-checker-hosts.py From Loki with GNU General Public License v3.0 | 6 votes |
def print_highlighted(line, hl_color=Back.WHITE): """ Print a highlighted line """ try: # Highlight positives colorer = re.compile(r'([^\s]+) POSITIVES: ([1-9]) ') line = colorer.sub(Fore.YELLOW + r'\1 ' + 'POSITIVES: ' + Fore.YELLOW + r'\2 ' + Style.RESET_ALL, line) colorer = re.compile(r'([^\s]+) POSITIVES: ([0-9]+) ') line = colorer.sub(Fore.RED + r'\1 ' + 'POSITIVES: ' + Fore.RED + r'\2 ' + Style.RESET_ALL, line) # Keyword highlight colorer = re.compile(r'([A-Z_]{2,}:)\s', re.VERBOSE) line = colorer.sub(Fore.BLACK + hl_color + r'\1' + Style.RESET_ALL + ' ', line) print line except Exception, e: pass
Example #6
Source File: vt-checker.py From Loki with GNU General Public License v3.0 | 6 votes |
def print_highlighted(line, hl_color=Back.WHITE): """ Print a highlighted line """ # Tags colorer = re.compile('(HARMLESS|SIGNED|MS_SOFTWARE_CATALOGUE)', re.VERBOSE) line = colorer.sub(Fore.BLACK + Back.GREEN + r'\1' + Style.RESET_ALL + ' ', line) colorer = re.compile('(SIG_REVOKED)', re.VERBOSE) line = colorer.sub(Fore.BLACK + Back.RED + r'\1' + Style.RESET_ALL + ' ', line) colorer = re.compile('(SIG_EXPIRED)', re.VERBOSE) line = colorer.sub(Fore.BLACK + Back.YELLOW + r'\1' + Style.RESET_ALL + ' ', line) # Extras colorer = re.compile('(\[!\])', re.VERBOSE) line = colorer.sub(Fore.BLACK + Back.CYAN + r'\1' + Style.RESET_ALL + ' ', line) # Standard colorer = re.compile('([A-Z_]{2,}:)\s', re.VERBOSE) line = colorer.sub(Fore.BLACK + hl_color + r'\1' + Style.RESET_ALL + ' ', line) print line
Example #7
Source File: models.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def line(self, level="info"): if level == "info": level = logging.INFO elif level == "debug": level = logging.DEBUG else: level = logging.INFO if self.isEnabledFor(level): self._log( level, Fore.BLACK + Style.BRIGHT + "-------------------------" + Style.RESET_ALL, [], )
Example #8
Source File: prints.py From PyFunceble with Apache License 2.0 | 5 votes |
def _colorify(self, data): """ Retun colored string. :param str data: The string to colorify. :return: A colored string. :rtype: str """ if self.template in ["Generic", "Less"]: # The template is in the list of template that need the coloration. if ( self.data_to_print[1].lower() in PyFunceble.STATUS.list.up or self.data_to_print[1].lower() in PyFunceble.STATUS.list.valid or self.data_to_print[1].lower() in PyFunceble.STATUS.list.sane ): # The status is in the list of up status. # We print the data with a green background. data = Fore.BLACK + Back.GREEN + data elif ( self.data_to_print[1].lower() in PyFunceble.STATUS.list.down or self.data_to_print[1].lower() in PyFunceble.STATUS.list.malicious ): # The status is in the list of down status. # We print the data with a red background. data = Fore.BLACK + Back.RED + data else: # The status is not in the list of up and down status. # We print the data with a cyan background. data = Fore.BLACK + Back.CYAN + data # We return the data. return data
Example #9
Source File: color_utils.py From jaide with GNU General Public License v2.0 | 5 votes |
def color(out_string, color='grn'): """ Highlight string for terminal color coding. Purpose: We use this utility function to insert a ANSI/win32 color code | and Bright style marker before a string, and reset the color and | style after the string. We then return the string with these | codes inserted. @param out_string: the string to be colored @type out_string: str @param color: a string signifying which color to use. Defaults to 'grn'. | Accepts the following colors: | ['blk', 'blu', 'cyn', 'grn', 'mag', 'red', 'wht', 'yel'] @type color: str @returns: the modified string, including the ANSI/win32 color codes. @rtype: str """ c = { 'blk': Fore.BLACK, 'blu': Fore.BLUE, 'cyn': Fore.CYAN, 'grn': Fore.GREEN, 'mag': Fore.MAGENTA, 'red': Fore.RED, 'wht': Fore.WHITE, 'yel': Fore.YELLOW, } try: init() return (c[color] + Style.BRIGHT + out_string + Fore.RESET + Style.NORMAL) except AttributeError: return out_string
Example #10
Source File: errorAnalysis.py From stanford-ctc with Apache License 2.0 | 5 votes |
def disp_err_corr(hyp_corr, ref_corr): hyp_str = '' ref_str = '' assert len(hyp_corr) == len(ref_corr) for k in xrange(len(hyp_corr)): if hyp_corr[k] == '[space]': hc = ' ' elif hyp_corr[k] == '<ins>': hc = Back.GREEN + ' ' + Back.RESET else: hc = hyp_corr[k] if ref_corr[k] == '[space]': rc = ' ' elif ref_corr[k] == '<del>': rc = Back.RED + ' ' + Back.RESET else: rc = ref_corr[k] if hc != rc and len(hc) == 1 and len(rc) == 1: hc = Back.BLUE + Fore.BLACK + hc + Fore.RESET + Back.RESET rc = Back.BLUE + Fore.BLACK + rc + Fore.RESET + Back.RESET hyp_str += hc ref_str += rc print hyp_str print ref_str
Example #11
Source File: demo06.py From colorama with BSD 3-Clause "New" or "Revised" License | 5 votes |
def main(): colorama.init() pos = lambda y, x: Cursor.POS(x, y) # draw a white border. print(Back.WHITE, end='') print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='') for y in range(MINY, 1+MAXY): print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='') print('%s%s' % (pos(MAXY, MINX), ' '*MAXX), end='') # draw some blinky lights for a while. for i in range(PASSES): print('%s%s%s%s%s' % (pos(randint(1+MINY,MAXY-1), randint(1+MINX,MAXX-1)), choice(FORES), choice(BACKS), choice(STYLES), choice(CHARS)), end='') # put cursor to top, left, and set color to white-on-black with normal brightness. print('%s%s%s%s' % (pos(MINY, MINX), Fore.WHITE, Back.BLACK, Style.NORMAL), end='')
Example #12
Source File: lokilogger.py From Loki with GNU General Public License v3.0 | 5 votes |
def print_welcome(self): if self.caller == 'main': print(Back.GREEN + " ".ljust(79) + Back.BLACK + Fore.GREEN) print(" __ ____ __ ______ ") print (" / / / __ \/ //_/ _/ ") print (" / /__/ /_/ / ,< _/ / ") print (" /____/\____/_/|_/___/ ") print (" ________ _____ ____ ") print (" / _/ __ \/ ___/ / __/______ ____ ___ ___ ____ ") print (" _/ // /_/ / /__ _\ \/ __/ _ `/ _ \/ _ \/ -_) __/ ") print (" /___/\____/\___/ /___/\__/\_,_/_//_/_//_/\__/_/ ") print (Fore.WHITE) print (" Copyright by Florian Roth, Released under the GNU General Public License") print (" Version %s" % __version__) print (" ") print (" DISCLAIMER - USE AT YOUR OWN RISK") print (" Please report false positives via https://github.com/Neo23x0/Loki/issues") print (" ") print (Back.GREEN + " ".ljust(79) + Back.BLACK) print (Fore.WHITE+''+Back.BLACK) else: print (" ") print (Back.GREEN + " ".ljust(79) + Back.BLACK + Fore.GREEN) print (" ") print (" LOKI UPGRADER ") print (" ") print (Back.GREEN + " ".ljust(79) + Back.BLACK) print (Fore.WHITE + '' + Back.BLACK)
Example #13
Source File: color_console.py From PyMicroChat with GNU General Public License v3.0 | 5 votes |
def black(s): """前景色:黑色 背景色:默认""" return Fore.BLACK + s
Example #14
Source File: internal.py From cheat.sh with MIT License | 5 votes |
def _reverse_palette(code): return { 1 : Fore.BLACK + _back_color(code), 2 : Style.DIM }
Example #15
Source File: colors.py From chepy with GNU General Public License v3.0 | 5 votes |
def yellow_background(s: str) -> str: # pragma: no cover """Yellow color string if tty Args: s (str): String to color Returns: str: Colored string """ if sys.stdout.isatty(): return Back.YELLOW + Fore.BLACK + s + Fore.RESET + Back.RESET else: return s
Example #16
Source File: __init__.py From pysslscan with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self): if colorama_init: colorama_init(autoreset=False) self.colors = { "RESET": Fore.RESET, "BLACK": Fore.BLACK, "RED": Fore.RED, "GREEN": Fore.GREEN, "YELLOW": Fore.YELLOW, "BLUE": Fore.BLUE, "MAGENTA": Fore.MAGENTA, "CYAN": Fore.CYAN #"GRAY": Fore.GRAY } else: CSI = "\33[" self.CSI = CSI self.colors = { "RESET": CSI + "0m", "BLACK": CSI + "0;30m", "RED": CSI + "0;31m", "GREEN": CSI + "0;32m", "YELLOW": CSI + "0;33m", "BLUE": CSI + "0;34m", "MAGENTA": CSI + "0;35m", "CYAN": CSI + "0;36m" #"GRAY": CSI + "0;37m" } self.mapped_colors = {} self.mapped_colors["default"] = { "DANGER": "RED", "ERROR": "RED", "OK": "GREEN", "SUCCESS": "GREEN", "WARNING": "YELLOW" }
Example #17
Source File: log.py From git-aggregator with GNU Affero General Public License v3.0 | 5 votes |
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
Example #18
Source File: genconfig.py From scrapple with MIT License | 5 votes |
def execute_command(self): """ The genconfig command depends on predefined `Jinja2 <http://jinja.pocoo.org/>`_ \ templates for the skeleton configuration files. Taking the --type argument from the \ CLI input, the corresponding template file is used. Settings for the configuration file, like project name, selector type and URL \ are taken from the CLI input and using these as parameters, the template is \ rendered. This rendered JSON document is saved as <project_name>.json. """ print(Back.GREEN + Fore.BLACK + "Scrapple Genconfig") print(Back.RESET + Fore.RESET) directory = os.path.join(scrapple.__path__[0], 'templates', 'configs') with open(os.path.join(directory, self.args['--type'] + '.txt'), 'r') as f: template_content = f.read() print("\n\nUsing the", self.args['--type'], "template\n\n") template = Template(template_content) settings = { 'projectname': self.args['<projectname>'], 'selector_type': self.args['--selector'], 'url': self.args['<url>'], 'levels': int(self.args['--levels']) } rendered = template.render(settings=settings) with open(self.args['<projectname>'] + '.json', 'w') as f: rendered_data = json.loads(rendered) json.dump(rendered_data, f, indent=3) print(Back.WHITE + Fore.RED + self.args['<projectname>'], ".json has been created" \ + Back.RESET + Fore.RESET, sep="")
Example #19
Source File: generate.py From scrapple with MIT License | 5 votes |
def execute_command(self): """ The generate command uses `Jinja2 <http://jinja.pocoo.org/>`_ templates \ to create Python scripts, according to the specification in the configuration \ file. The predefined templates use the extract_content() method of the \ :ref:`selector classes <implementation-selectors>` to implement linear extractors \ and use recursive for loops to implement multiple levels of link crawlers. This \ implementation is effectively a representation of the traverse_next() \ :ref:`utility function <implementation-utils>`, using the loop depth to \ differentiate between levels of the crawler execution. According to the --output_type argument in the CLI input, the results are \ written into a JSON document or a CSV document. The Python script is written into <output_filename>.py - running this file \ is the equivalent of using the Scrapple :ref:`run command <command-run>`. """ print(Back.GREEN + Fore.BLACK + "Scrapple Generate") print(Back.RESET + Fore.RESET) directory = os.path.join(scrapple.__path__[0], 'templates', 'scripts') with open(os.path.join(directory, 'generate.txt'), 'r') as f: template_content = f.read() template = Template(template_content) try: with open(self.args['<projectname>'] + '.json', 'r') as f: config = json.load(f) if self.args['--output_type'] == 'csv': from scrapple.utils.config import extract_fieldnames config['fields'] = str(extract_fieldnames(config)) config['output_file'] = self.args['<output_filename>'] config['output_type'] = self.args['--output_type'] rendered = template.render(config=config) with open(self.args['<output_filename>'] + '.py', 'w') as f: f.write(rendered) print(Back.WHITE + Fore.RED + self.args['<output_filename>'], \ ".py has been created" + Back.RESET + Fore.RESET, sep="") except IOError: print(Back.WHITE + Fore.RED + self.args['<projectname>'], ".json does not ", \ "exist. Use ``scrapple genconfig``." + Back.RESET + Fore.RESET, sep="")
Example #20
Source File: web.py From scrapple with MIT License | 5 votes |
def execute_command(self): """ The web command runs the Scrapple web interface through a simple \ `Flask <http://flask.pocoo.org>`_ app. When the execute_command() method is called from the \ :ref:`runCLI() <implementation-cli>` function, it starts of two simultaneous \ processes : - Calls the run_flask() method to start the Flask app on port 5000 of localhost - Opens the web interface on a web browser The '/' view of the Flask app, opens up the Scrapple web interface. This \ provides a basic form, to fill in the required configuration file. On submitting \ the form, it makes a POST request, passing in the form in the request header. \ This form is passed to the form_to_json() \ :ref:`utility function <implementation-utils>`, where the form is converted into \ the resultant JSON configuration file. Currently, closing the web command execution requires making a keyboard interrupt \ on the command line after the web interface has been closed. """ print(Back.GREEN + Fore.BLACK + "Scrapple Web Interface") print(Back.RESET + Fore.RESET) p1 = Process(target = self.run_flask) p2 = Process(target = lambda : webbrowser.open('http://127.0.0.1:5000')) p1.start() p2.start()
Example #21
Source File: outputparser.py From screeps_console with MIT License | 5 votes |
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
Example #22
Source File: munin_stdout.py From munin with Apache License 2.0 | 5 votes |
def printKeyLine(line): """ Print a given string as a separator line :param line: :return: """ print(Fore.BLACK + Back.WHITE) print("{0}".format(line).ljust(80) + Style.RESET_ALL) print("")
Example #23
Source File: munin_stdout.py From munin with Apache License 2.0 | 5 votes |
def printSeparator(count, total, color, rating): """ Print a separator line status infos :param count: :param total: :return: """ print(Fore.BLACK + color) print(" {0} / {1} > {2}".format(count+1, total, rating.title()).ljust(80) + Style.RESET_ALL)
Example #24
Source File: personality.py From Jarvis with MIT License | 5 votes |
def __call__(self, jarvis, s): prompt = "{black}Q{Q_id} {cyan}{left} {black}--- {green}{right}" prompt_formatter = { 'cyan': Fore.CYAN, 'black': Fore.BLACK, 'green': Fore.GREEN } jarvis.say("Start personality test..", color=Fore.BLACK) jarvis.say(self.instruction) for i, (Q_id, left, right) in enumerate(self.Q): prompt_formatter['Q_id'] = i prompt_formatter['left'] = left prompt_formatter['right'] = right jarvis.say(prompt.format(**prompt_formatter)) user_input = jarvis.input_number( prompt="Enter your choice on the scale of 1-5:\n", rmin=1, rmax=5, color=Fore.BLUE, rtype=int) self.answers[Q_id] = user_input self.get_scores() jarvis.say( "{}Your personality is: {}{}{}{}".format( Fore.BLUE, Fore.BLACK, Back.MAGENTA, self.type, Style.RESET_ALL)) jarvis.say( "Redirecting to your personality analysis\ in 3s...", color=Fore.BLUE) time.sleep(3) self.open_analysis()
Example #25
Source File: cricket.py From Jarvis with MIT License | 5 votes |
def scorecard(self, index): selected_match = self.all_match_data[index] data = self.c.scorecard(self.matches[index]['id']) card = {} card['matchinfo'] = "{}, {}".format( selected_match['srs'], selected_match['mnum']) card['status'] = "{}".format(selected_match['status']) card['scorecard'] = data['scorecard'] text = '' text += Fore.LIGHTYELLOW_EX + \ card['matchinfo'] + '\n' + card['status'] + '\n\n' text += Fore.BLACK + '*' * 35 + '\n\n' for scr in reversed(card['scorecard']): text += Fore.LIGHTYELLOW_EX + "{}\nInnings: {}\n{}/{} in {} overs\n\n".format( scr['batteam'], scr['inng_num'], scr['runs'], scr['wickets'], scr['overs']) text += Fore.BLUE + "Batting\n" text += Fore.RED + \ "{:<17} {:<3} {:<3} {:<3} {}\n\n".format('Name', 'R', 'B', '4', '6') for b in scr['batcard']: text += Fore.BLACK + "{:<17} {:<3} {:<3} {:<3} {}\n{}\n\n".format( b['name'], b['runs'], b['balls'], b['fours'], b['six'], b['dismissal']) text += Fore.LIGHTYELLOW_EX + "-" * 35 + "\n\n" text += Fore.BLUE + "Bowling\n" text += Fore.RED + \ "{:<17} {:<5} {:<3} {:<3} {}\n\n".format('Name', 'O', 'M', 'R', 'W') for b in scr['bowlcard']: text += Fore.BLACK + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format( b['name'], b['overs'], b['maidens'], b['runs'], b['wickets']) text += Fore.BLUE + '*' * 35 + '\n\n' return text
Example #26
Source File: cricket.py From Jarvis with MIT License | 5 votes |
def live_score(self, index): if self.all_match_data[index]['mchstate'] == 'preview': return(Fore.RED + "MATCH YET TO BEGIN") selected_match = self.all_match_data[index] data = self.c.livescore(self.matches[index]['id']) score = {} score['matchinfo'] = "{}, {}".format( selected_match['srs'], selected_match['mnum']) score['status'] = "{}".format(selected_match['status']) score['bowling'] = data['bowling'] score['batting'] = data['batting'] text = '' text += Fore.LIGHTYELLOW_EX + \ score['matchinfo'] + '\n' + score['status'] + '\n\n' text += Fore.BLUE + score['batting']['team'] + Fore.BLACK for scr in reversed(score['batting']['score']): text += " :- {}/{} in {} overs\n".format( scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['batting']['batsman']): text += "{} : {}({}) \n".format( b['name'].strip('*'), b['runs'], b['balls']) text += Fore.BLUE + '\n' + score['bowling']['team'] + Fore.BLACK for scr in reversed(score['bowling']['score']): text += " :- {}/{} in {} overs\n".format( scr['runs'], scr['wickets'], scr['overs']) for b in reversed(score['bowling']['bowler']): text += "{} : {}/{} \n".format(b['name'].strip('*'), b['wickets'], b['runs']) text += Fore.RESET return text
Example #27
Source File: run.py From scrapple with MIT License | 4 votes |
def execute_command(self): """ The run command implements the web content extractor corresponding to the given \ configuration file. The execute_command() validates the input project name and opens the JSON \ configuration file. The run() method handles the execution of the extractor run. The extractor implementation follows these primary steps : 1. Selects the appropriate :ref:`selector class <implementation-selectors>` through \ a dynamic dispatch, with the selector_type argument from the CLI input. #. Iterate through the data section in level-0 of the configuration file. \ On each data item, call the extract_content() method from the selector class to \ extract the content according to the specified extractor rule. #. If there are multiple levels of the extractor, i.e, if there is a 'next' \ attribute in the configuration file, call the traverse_next() \ :ref:`utility function <implementation-utils>` and parse through successive levels \ of the configuration file. #. According to the --output_type argument, the result data is saved in a JSON \ document or a CSV document. """ try: self.args['--verbosity'] = int(self.args['--verbosity']) if self.args['--verbosity'] not in [0, 1, 2]: raise ValueError if self.args['--verbosity'] > 0: print(Back.GREEN + Fore.BLACK + "Scrapple Run") print(Back.RESET + Fore.RESET) import json with open(self.args['<projectname>'] + '.json', 'r') as f: self.config = json.load(f) validate_config(self.config) self.run() except ValueError: print(Back.WHITE + Fore.RED + "Use 0, 1 or 2 for verbosity." \ + Back.RESET + Fore.RESET, sep="") except IOError: print(Back.WHITE + Fore.RED + self.args['<projectname>'], ".json does not ", \ "exist. Use ``scrapple genconfig``." + Back.RESET + Fore.RESET, sep="") except InvalidConfigException as e: print(Back.WHITE + Fore.RED + e + Back.RESET + Fore.RESET, sep="")
Example #28
Source File: hugin.py From munin with Apache License 2.0 | 4 votes |
def main(): init(autoreset=False) print(Style.RESET_ALL) print(Fore.BLACK + Back.WHITE) print(" _ _ _ _ ______ _____ ______ ".ljust(80)) print(" | | | | | | | | | | ____ | | | | \ \ (.\\ ".ljust(80)) print(" | |--| | | | | | | | | | | | | | | | |/(\\ ".ljust(80)) print(" |_| |_| \_|__|_| |_|__|_| _|_|_ |_| |_| \\ \\\\".ljust(80)) print(" \" \"'\\ ".ljust(80)) print(" ".ljust(80)) print(" Result Checker for Virustotal Retrohunts".ljust(80)) print((" " + __AUTHOR__ + " - " + __VERSION__ + "").ljust(80)) print(" ".ljust(80) + Style.RESET_ALL) print(Style.RESET_ALL + " ") parser = argparse.ArgumentParser(description='Retrohunt Checker') parser.add_argument('-r', help='Name for the queried retrohunt', metavar='retrohunt-name', default='') parser.add_argument('-i', help='Name of the ini file that holds the VT API key', metavar='ini-file', default=os.path.dirname(os.path.abspath(__file__)) + '/munin.ini') parser.add_argument('--csv-path', help='Write a CSV with the results', default='retrohunt_results.csv') parser.add_argument('--debug', action='store_true', default=False, help='Debug output') parser.add_argument('--no-comments', help='Skip VirusTotal comments', action='store_true', default=False) args = parser.parse_args() # PyMISP error handling > into Nirvana logger = logging.getLogger("pymisp") logger.setLevel(logging.CRITICAL) if args.debug: logger.setLevel(logging.DEBUG) # Read the config file config = configparser.ConfigParser() try: config.read(args.i) munin_vt.VT_PUBLIC_API_KEY = config['DEFAULT']['VT_PUBLIC_API_KEY'] try: connections.setProxy(config['DEFAULT']['PROXY']) except KeyError as e: print("[E] Your config misses the PROXY field - check the new munin.ini template and add it to your " "config to avoid this error.") except Exception as e: traceback.print_exc() print("[E] Config file '%s' not found or missing field - check the template munin.ini if fields have " "changed" % args.i) print("[+] Retrieving Retrohunt results ...") found_files = munin_vt.getRetrohuntResults(args.r, args.no_comments, args.debug) print("[+] Retrohunt results retrieved") csv_filename = args.csv_path writeCSVHeader(csv_filename) for i, file_info in enumerate(found_files): printResult(file_info, i, len(found_files)) writeCSV(file_info, csv_filename)
Example #29
Source File: test_output_prints.py From PyFunceble with Apache License 2.0 | 4 votes |
def test_colorify(self): """ Tests the method which colors a line depending of the status. """ # pylint: disable=protected-access expected = False actual = self.file_instance.exists() self.assertEqual(expected, actual) # Test with a template that is not designed for colorify expected = self.to_print["basic_string"] actual = Prints(None, "Hehehe", output_file=None, only_on_file=False)._colorify( self.to_print["basic_string"] ) self.assertEqual(expected, actual) # Test with a template that is designed for colorify + Status is UP expected = Fore.BLACK + Back.GREEN + self.to_print["basic_string"] actual = Prints( ["This is a test", PyFunceble.STATUS.official.up], "Generic", output_file=None, only_on_file=False, )._colorify(self.to_print["basic_string"]) self.assertEqual(expected, actual) # Test with a template that is designed for colorify + Status is DOWN expected = Fore.BLACK + Back.RED + self.to_print["basic_string"] actual = Prints( ["This is a test", PyFunceble.STATUS.official.down], "Generic", output_file=None, only_on_file=False, )._colorify(self.to_print["basic_string"]) self.assertEqual(expected, actual) # Test with a template that is designed for colorify + Status is # UNKNOWN or INVALID expected = Fore.BLACK + Back.CYAN + self.to_print["basic_string"] actual = Prints( ["This is a test", PyFunceble.STATUS.official.invalid], "Generic", output_file=None, only_on_file=False, )._colorify(self.to_print["basic_string"]) self.assertEqual(expected, actual)
Example #30
Source File: log.py From git-aggregator with GNU Affero General Public License v3.0 | 4 votes |
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