Python colorama.Back.GREEN Examples

The following are 25 code examples of colorama.Back.GREEN(). 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.Back , or try the search function .
Example #1
Source File: bmi.py    From Jarvis with MIT License 6 votes vote down vote up
def print_body_state(self, jarvis, bmi):
        """
        According the bmi number, print_body_state finds out the state of the body
        and prints it to the user using colorama library for some coloring
        """
        print("BMI:", str(bmi))
        if bmi < 16:
            print(Back.RED, " " * 2, Style.RESET_ALL)
            jarvis.say('Severe thinness')
        elif bmi < 18.5:
            print(Back.YELLOW, " " * 2, Style.RESET_ALL)
            jarvis.say('Mild thinness')
        elif bmi < 25:
            print(Back.GREEN, " " * 2, Style.RESET_ALL)
            jarvis.say('Healthy')
        elif bmi < 30:
            print(Back.YELLOW, " " * 2, Style.RESET_ALL)
            jarvis.say('Pre-obese')
        else:
            print(Back.RED, " " * 2, Style.RESET_ALL)
            jarvis.say('Obese') 
Example #2
Source File: munin_stdout.py    From munin with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: example_python_operator.py    From airflow with Apache License 2.0 6 votes vote down vote up
def callable_virtualenv():
    """
    Example function that will be performed in a virtual environment.

    Importing at the module level ensures that it will not attempt to import the
    library before it is installed.
    """
    from colorama import Fore, Back, Style
    from time import sleep
    print(Fore.RED + 'some red text')
    print(Back.GREEN + 'and with a green background')
    print(Style.DIM + 'and in dim text')
    print(Style.RESET_ALL)
    for _ in range(10):
        print(Style.DIM + 'Please wait...', flush=True)
        sleep(10)
    print('Finished') 
Example #4
Source File: install.py    From Yugioh-bot with MIT License 6 votes vote down vote up
def install_tesseract():
    is_installed, message = check_if_tesseract_installed()
    if is_installed:
        print(Back.GREEN + message + Back.CYAN)
        return
    try:
        os.stat(TESSERACT_SETUP_FILE)
        command_runner(TESSERACT_SETUP_FILE)
    except FileNotFoundError:
        setup_file = download_tesseract()
    try:
        print(Style.BRIGHT + Back.CYAN + 'Make sure to point the installer to the following directory: {}'.format(
            os.path.join(os.getcwd(), 'bin', 'tess')))
        command_runner(setup_file)
    except FileNotFoundError:
        print("Oooo something happened when I downloaded the file, rerun this script") 
Example #5
Source File: install.py    From Yugioh-bot with MIT License 6 votes vote down vote up
def download_tesseract_source(tess_download):
    try:
        os.stat(tess_download.text_content())
        print(Back.GREEN + "Found file {} locally, using instead".format(
            tess_download.text_content()))
        print(Back.GREEN + "Skipping Download" + Style.RESET_ALL)
        return tess_download.text_content()
    except FileNotFoundError:
        pass
    url = domain_tess + tess_download.get('href')
    print(Back.GREEN + Style.BRIGHT + "Downloading {}".format(url))
    response = requests.get(url, stream=True)
    total_size = int(response.headers.get('content-length', 0))
    with tqdm(total=total_size, unit='B', unit_scale=True) as pbar:
        with open(tess_download.text_content(), "wb") as f:
            for data in response.iter_content(chunk_size=1024 * 4):
                f.write(data)
                pbar.update(len(data))
    return tess_download.text_content() 
Example #6
Source File: install.py    From Yugioh-bot with MIT License 6 votes vote down vote up
def copy_nox_bin_files():
    adb_file_name = 'nox_adb.exe'
    dll_file_name = 'AdbWinApi.dll'
    path = NOX_BIN
    try:
        os.stat(os.path.join(path, adb_file_name))
        os.stat(os.path.join(path, dll_file_name))
    except FileNotFoundError:
        try:
            path = NOX_BIN_OTHER
            os.stat(os.path.join(path, adb_file_name))
            os.stat(os.path.join(path, dll_file_name))
        except FileNotFoundError:
            print(Fore.RED + """Cannot find the required nox files in either
                    {} or {}, help is requireed""".format(NOX_BIN_OTHER, NOX_BIN))
            return
    copyfile(os.path.join(path, adb_file_name), os.path.join('bin', 'adb.exe'))
    copyfile(os.path.join(path, dll_file_name), os.path.join('bin', dll_file_name))
    print(Back.GREEN + "Copied [{}] into bin folder".format(', '.join([adb_file_name, dll_file_name])) + Back.CYAN) 
Example #7
Source File: debuggers.py    From bintut with GNU General Public License v3.0 6 votes vote down vote up
def print_asm(self):
        command = 'u {} l10'.format(self.env.IP)
        try:
            asms = self.execute(command)
        except self.pykd.DbgException as error:
            self.logger.error(error)
        else:
            ip = self.pykd.reg(self.env.IP)
            for line in asms.splitlines()[1:]:
                try:
                    address, opcode, ins = line.split(None, 2)
                except ValueError as error:
                    print(red('{}: {}'.format(line, error)))
                else:
                    line = '{:25} {:25} {}'.format(
                        cyan(address, res=False),
                        yellow(opcode, res=False), red(ins))
                    if int(address, 16) == ip:
                        print(Back.GREEN + line)
                    else:
                        print(line) 
Example #8
Source File: vt-checker.py    From Loki with GNU General Public License v3.0 6 votes vote down vote up
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 #9
Source File: install.py    From Yugioh-bot with MIT License 5 votes vote down vote up
def check_required_packages():
    if SKIP_PIP_TEST:
        return
    installed_packages = pkg_resources.working_set
    packages = {}
    for package in installed_packages:
        packages[package.project_name] = package.version
    with open('requirements.txt') as f:
        required = list(map(lambda x: x.split('=')[0].replace('>', ''), f.read().splitlines()))
    required = filter(lambda x: not '#' in x, required)
    all_installed = True
    for x in required:
        if x in ['scikit_image', 'scikit_learn', 'opencv_contrib_python']:
            continue
        if x not in packages:
            print(Back.YELLOW + "Not in pip {}".format(x))
            all_installed = False
    try:
        import sklearn
        import skimage
        import cv2
    except ImportError as e:
        print(Back.RED + "Import error for package")
        print(Back.Red + e)
    if not all_installed:
        print(
            Back.RED + Style.BRIGHT + "Not all packages required were found\ntry running `pip -r requirements.txt` again" + Back.CYAN)
    else:
        print(Back.GREEN + "All required packages found" + Back.CYAN)


# Commands to Run 
Example #10
Source File: colors.py    From VxAPI with GNU General Public License v3.0 5 votes vote down vote up
def success(text):
        text = str(text)

        return Back.GREEN + text + Style.RESET_ALL if Color.is_atty() else text 
Example #11
Source File: install.py    From Yugioh-bot with MIT License 5 votes vote down vote up
def download_tesseract():
    r = requests.get(domain_tess)
    dom = html.fromstring(r.text)
    links = dom.cssselect('a')
    tess_links = list(filter(lambda x: re.search(
        tess_search, x.text_content()), links))
    original_link = list(filter(lambda x: x.text_content()
                                          == tess_tested_against, links))
    if len(original_link) == 1:
        tess_download = original_link[0]
        print(Back.GREEN + 'Found Expected Tesseract on site ({}), downloading'.format(
            tess_tested_against))
        return download_tesseract_source(tess_download)
    elif len(tess_links) > 0:
        print(Back.GREEN + "Found Tesseract links but none of them were tested against this bot")
        print(Back.GREEN + "Choose one of the following to install")
        for index, link in enumerate(tess_links):
            print(Back.GREEN + "{}. {}".format(index + 1, link.text_content()))
        while True:
            val = input(Back.GREEN + "Choose: ")
            if int(val) in range(1, len(tess_links) + 1):
                tess_download = tess_links[int(val) - 1]
                break
            print(Style.BRIGHT + Style.YELLOW + "Invalid value {}".format(val))
        return download_tesseract_source(tess_download)
    else:
        print(Style.BRIGHT + Style.RED +
              "Found no Tesseract links to download get help or download manually")
        return None 
Example #12
Source File: prints.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: helper.py    From PRET with GNU General Public License v2.0 5 votes vote down vote up
def fuzzed(self, path, cmd, opt):
      opt1, opt2, opt3 = opt
      if isinstance(opt1, bool): opt1 = (Back.GREEN + str(opt1) + Back.BLUE + "   ")\
                                 if opt1 else (Back.RED + str(opt1) + Back.BLUE + "  ")
      if isinstance(opt2, bool): opt2 = (Back.GREEN + str(opt2) + Back.BLUE + "   ")\
                                 if opt2 else (Back.RED + str(opt2) + Back.BLUE + "  ")
      if isinstance(opt3, bool): opt3 = (Back.GREEN + str(opt3) + Back.BLUE + "   ")\
                                 if opt3 else (Back.RED + str(opt3) + Back.BLUE + "  ")
      opt = opt1, opt2, opt3
      self.info("%-35s %-12s %-7s %-7s %-7s" % ((path, cmd) + opt))

  # show captured jobs 
Example #14
Source File: helper.py    From PRET with GNU General Public License v2.0 5 votes vote down vote up
def green(self, msg):
    if msg: print(Back.GREEN + msg + Style.RESET_ALL)

  # show error message 
Example #15
Source File: errorAnalysis.py    From stanford-ctc with Apache License 2.0 5 votes vote down vote up
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 #16
Source File: lokilogger.py    From Loki with GNU General Public License v3.0 5 votes vote down vote up
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 #17
Source File: color_console.py    From PyMicroChat with GNU General Public License v3.0 5 votes vote down vote up
def white_green(s):
        """前景色:白色  背景色:绿色"""
        return Fore.WHITE + Back.GREEN + s 
Example #18
Source File: color_console.py    From PyMicroChat with GNU General Public License v3.0 5 votes vote down vote up
def green(s):
        """前景色:绿色  背景色:默认"""
        return Fore.GREEN + s 
Example #19
Source File: genconfig.py    From scrapple with MIT License 5 votes vote down vote up
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 #20
Source File: generate.py    From scrapple with MIT License 5 votes vote down vote up
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 #21
Source File: web.py    From scrapple with MIT License 5 votes vote down vote up
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 #22
Source File: debuggers.py    From bintut with GNU General Public License v3.0 4 votes vote down vote up
def print_asm(self):
        def repr_asm(name, head, asm, pc):
            child = self.gdb.selected_inferior()
            mem = child.read_memory(asm['addr'], asm['length'])
            addr = hex(asm['addr']).strip('L')
            if name:
                delta = asm['addr'] - int(head, 16)
                delta = '<{}+{}>'.format(name, delta)
                fmt = '    {:20} {:24} {:25} {}'
            else:
                delta = ''
                fmt = '    {:36}{}{:25} {}'
            line = fmt.format(
                cyan(addr, res=False), yellow(delta, res=False),
                green(hexlify(mem).decode('utf-8'), res=False),
                red(asm['asm']), res=False)
            if asm['addr'] == pc:
                return Back.GREEN + '==> ' + line.strip()
            else:
                return line
        try:
            ip = self.get_reg(self.env.IP)
            self.logger.debug('ip: %s', ip)
            pc = int(ip, 16)
            self.logger.debug('pc: %s', pc)
        except TypeError as error:
            self.logger.error(error)
        try:
            frame = self.gdb.selected_frame()
            self.logger.debug('frame: %s', frame)
            name = frame.name()
            if name:
                head = self.execute('p {}'.format(name)).split()[-2]
            else:
                head = None
            self.logger.debug('name: %s head: %s', name, head)
            arch = frame.architecture()
            asms = arch.disassemble(pc, pc+32)
        except (self.gdb.MemoryError, self.gdb.error) as error:
            self.logger.error(error)
        else:
            found = False
            for index, asm in enumerate(asms):
                if asm['addr'] == pc:
                    before = asms[index-8:index]
                    just = asms[index]
                    after = asms[index+1:index+1+8]
                    for one in before + [just] + after:
                        print(repr_asm(name, head, one, pc))
                    found = True
                    break
            if not found:
                raise RuntimeError('pc not found') 
Example #23
Source File: test_output_prints.py    From PyFunceble with Apache License 2.0 4 votes vote down vote up
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 #24
Source File: run.py    From scrapple with MIT License 4 votes vote down vote up
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 #25
Source File: munin_stdout.py    From munin with Apache License 2.0 4 votes vote down vote up
def printResult(info, count, total):
    """
    prints the result block
    :param info: all collected info
    :param count: counter (number of samples checked)
    :param total: total number of lines to check
    :return:
    """
    # Rating and Color
    info["res_color"] = Back.CYAN

    # If VT returned results
    if "total" in info:
        info["res_color"] = Back.GREEN
        if info["positives"] > 0:
            info["res_color"] = Back.YELLOW
        if info["positives"] > 10:
            info["res_color"] = Back.RED

    # Head line
    printSeparator(count, total, info['res_color'], info["rating"])
    headline = "HASH: {0}".format(info["hash"])
    if 'comment' in info and info['comment'] != '':
        headline += " COMMENT: {0}".format(info['comment'])
    if 'matching_rule' in info and info['matching_rule'] != '':
        headline += " RULE: {0}".format(info['matching_rule'])
    printHighlighted(headline)

    # More VT info
    if "total" in info:
        # Result
        info["result"] = "%s / %s" % (info["positives"], info["total"])
        if info["virus"] != "-":
            printHighlighted("VIRUS: {0}".format(info["virus"]))
        printHighlighted("TYPE: {1} SIZE: {2} FILENAMES: {0}".format(removeNonAsciiDrop(info["filenames"]),
                                                                     info['filetype'],
                                                                     info['filesize']))

        # Tags to show
        tags = ""
        if isinstance(info['tags'], list):
            tags = " ".join(map(lambda x: x.upper(), info['tags']))
        # Extra Info
        printPeInfo(info)
        printHighlighted("FIRST: {0} LAST: {1} SUBMISSIONS: {5} REPUTATION: {6}\nCOMMENTS: {2} USERS: {3} TAGS: {4}".format(
            info["first_submitted"],
            info["last_submitted"],
            info["comments"],
            ', '.join(info["commenter"]),
            tags,
            info["times_submitted"],
            info["reputation"]
        ), tag_color=True)

    # Print the highlighted result line
    printHighlighted("RESULT: %s" % (info["result"]), hl_color=info["res_color"])