Python colorama.Fore.RESET Examples

The following are 30 code examples of colorama.Fore.RESET(). 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: cb_tools.py    From Forager with MIT License 7 votes vote down vote up
def run_feed_server():
    #stands up the feed server, points to the CB/json_feeds dir
    chdir('data/json_feeds/')
    port = 8000
    handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(("", port), handler)

    try:
        print((Fore.GREEN + '\n[+]' + Fore.RESET), end=' ')
        print(('Feed Server listening at http://%s:8000' % gethostname()))
        httpd.serve_forever()
    except:
        print((Fore.RED + '\n[-]' + Fore.RESET), end=' ')
        print("Server exited")

    return 
Example #2
Source File: login.py    From maubot with GNU Affero General Public License v3.0 7 votes vote down vote up
def login(server, username, password, alias) -> None:
    data = {
        "username": username,
        "password": password,
    }
    try:
        with urlopen(f"{server}/_matrix/maubot/v1/auth/login",
                     data=json.dumps(data).encode("utf-8")) as resp_data:
            resp = json.load(resp_data)
            config["servers"][server] = resp["token"]
            if not config["default_server"]:
                print(Fore.CYAN, "Setting", server, "as the default server")
                config["default_server"] = server
            if alias:
                config["aliases"][alias] = server
            save_config()
            print(Fore.GREEN + "Logged in successfully")
    except HTTPError as e:
        try:
            err = json.load(e)
        except json.JSONDecodeError:
            err = {}
        print(Fore.RED + err.get("error", str(e)) + Fore.RESET) 
Example #3
Source File: print_ast.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
def walker(node, source_lines, indent=''):
    """Recursively visit the ast in a preorder traversal."""

    node_name = str(node)[0:str(node).index('(')]
    value = None
    if hasattr(node, 'value'):
        if '(' in str(node.value):
            value = str(node.value)[0:str(node.value).index('(')]
        else:
            value = node.value

    name = node.name if hasattr(node, 'name') else None
    print('{}{} {} (name: {}, value: {})'.format(
        indent, CHAR_TUBE, node_name, name, value))

    lines = [line for line in node.as_string().split('\n')]
    for line in lines:
        print(indent + FILL + '>>>' + Fore.BLUE + line + Fore.RESET)

    for child in node.get_children():
        walker(child, source_lines, indent + FILL + CHAR_PIPE) 
Example #4
Source File: logs.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def watch(self, raw_args):
        def tail(_file):
            _file.seek(0, 2)      # Go to the end of the file
            while True:
                line = _file.readline()
                if not line:
                    time.sleep(0.1)
                    continue
                yield line

        _file = open(_log_path, 'r')
        print(Fore.GREEN + '[bitmask] ' +
              Fore.RESET + 'Watching log file %s' % _log_path)
        for line in _file.readlines():
            print line,
        for line in tail(_file):
            print line, 
Example #5
Source File: logging_helpers.py    From dephell with MIT License 6 votes vote down vote up
def format(self, record):
        # add color
        if self.colors and record.levelname in COLORS:
            start = COLORS[record.levelname]
            record.levelname = start + record.levelname + Fore.RESET
            record.msg = Fore.WHITE + record.msg + Fore.RESET

        # add extras
        if self.extras:
            extras = merge_record_extra(record=record, target=dict(), reserved=RESERVED_ATTRS)
            record.extras = ', '.join('{}={}'.format(k, v) for k, v in extras.items())
            if record.extras:
                record.extras = Fore.MAGENTA + '({})'.format(record.extras) + Fore.RESET

        # hide traceback
        if not self.traceback:
            record.exc_text = None
            record.exc_info = None
            record.stack_info = None

        return super().format(record) 
Example #6
Source File: output.py    From h2t with MIT License 6 votes vote down vote up
def print_line(message, level=1, category = None, title = None, status=False):
    sts = get_status(category, status)

    if sts == 'applied':
        color = Fore.GREEN
        pre = '[+] '
    elif sts == 'touse':
        color = Fore.YELLOW
        pre = '[+] '
    elif sts == 'toremove':
        color = Fore.RED
        pre = '[-] '
    else:
        color = ''
        pre = ''

    if title:
        print(' '*4*level + Style.BRIGHT + title + ': ' + Style.RESET_ALL + message)
    else:
        print(' '*4*level + color + Style.BRIGHT + pre + Fore.RESET + message) 
Example #7
Source File: output.py    From drydock with GNU General Public License v2.0 6 votes vote down vote up
def print_results(self,results):
    try:
      if results['status'] == 'Pass':
        print ("Status: " + Fore.GREEN + 'Pass' + Fore.RESET)
      elif results['status'] == 'Fail':
        print ("Status: " + Fore.RED + 'Fail' + Fore.RESET)
    except KeyError:
      pass
    except TypeError:
      pass
    print "Description: " + results['descr']
    try:
      res = str(results['output'])
      print "Output: "
      print(Style.DIM + res + Style.RESET_ALL)
    except KeyError:
      pass
    print "\n" 
Example #8
Source File: umbrella.py    From Jarvis with MIT License 6 votes vote down vote up
def main(city=0):
    send_url = (
        "http://api.openweathermap.org/data/2.5/forecast/daily?q={0}&cnt=1"
        "&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=metric".format(city)
    )
    r = requests.get(send_url)
    j = json.loads(r.text)
    rain = j['list'][0]['weather'][0]['id']
    if rain >= 300 and rain <= 500:  # In case of drizzle or light rain
        print(
            Fore.CYAN
            + "It appears that you might need an umbrella today."
            + Fore.RESET)
    elif rain > 700:
        print(
            Fore.CYAN
            + "Good news! You can leave your umbrella at home for today!"
            + Fore.RESET)
    else:
        print(
            Fore.CYAN
            + "Uhh, bad luck! If you go outside, take your umbrella with you."
            + Fore.RESET) 
Example #9
Source File: main.py    From network-programmability-stream with MIT License 6 votes vote down vote up
def main():
    start_time = time.time()
    nr = InitNornir("config.yaml", configure_logging=False)
    # result = nr.run(
    #     task=netmiko_send_command,
    #     command_string="show cdp neighbors detail",
    #     use_textfsm=True,
    # )
    nr.run(
        task=update_lldp_neighbors,
    )
    logger.info("LLDP details were successfully fetched using RESTCONF and OPENCONFIG")
    milestone = time.time()
    time_to_run = milestone - start_time
    print(
        f"{Fore.RED}It took {time_to_run:.2f} seconds to get and parse LLDP details"
        f"{Fore.RESET}"
    )
    graph, edge_labels = build_graph(nr.inventory.hosts.values())
    draw_and_save_topology(graph, edge_labels)
    time_to_run = time.time() - milestone
    print(
        f"{Fore.RED}It took additional {time_to_run:.2f} seconds "
        f"to draw and save the network topology{Fore.RESET}"
    ) 
Example #10
Source File: supersede_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def perform(self, requests=None):
        for stage_info, code, request in self.api.dispatch_open_requests(requests):
            action = request.find('action')
            target_package = action.find('target').get('package')
            if code == 'unstage':
                # Technically, the new request has not been staged, but superseded the old one.
                code = None
            verbage = self.CODE_MAP[code]
            if code is not None:
                verbage += ' in favor of'
            print('request {} for {} {} {} in {}'.format(
                request.get('id'),
                Fore.CYAN + target_package + Fore.RESET,
                verbage,
                stage_info['rq_id'],
                Fore.YELLOW + stage_info['prj'] + Fore.RESET)) 
Example #11
Source File: build.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def build(path: str, output: str, upload: bool, server: str) -> None:
    meta = read_meta(path)
    if not meta:
        return
    if output or not upload:
        output = read_output_path(output, meta)
        if not output:
            return
    else:
        output = BytesIO()
    os.chdir(path)
    write_plugin(meta, output)
    if isinstance(output, str):
        print(f"{Fore.GREEN}Plugin built to {Fore.CYAN}{output}{Fore.GREEN}.{Fore.RESET}")
    else:
        output.seek(0)
    if upload:
        upload_plugin(output, server) 
Example #12
Source File: build.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def read_meta(path: str) -> Optional[PluginMeta]:
    try:
        with open(os.path.join(path, "maubot.yaml")) as meta_file:
            try:
                meta_dict = yaml.load(meta_file)
            except YAMLError as e:
                print(Fore.RED + "Failed to build plugin: Metadata file is not YAML")
                print(Fore.RED + str(e) + Fore.RESET)
                return None
    except FileNotFoundError:
        print(Fore.RED + "Failed to build plugin: Metadata file not found" + Fore.RESET)
        return None
    try:
        meta = PluginMeta.deserialize(meta_dict)
    except SerializerError as e:
        print(Fore.RED + "Failed to build plugin: Metadata file is not valid")
        print(Fore.RED + str(e) + Fore.RESET)
        return None
    return meta 
Example #13
Source File: bitmask_cli.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def execute():
    cfg = Configuration(".bitmaskctl")
    print_json = '--json' in sys.argv

    cli = BitmaskCLI(cfg)
    cli.data = ['core', 'version']
    args = None if '--noverbose' in sys.argv else ['--verbose']

    if should_start(sys.argv):
        timeout_fun = cli.start
    else:
        def status_timeout(args):
            raise RuntimeError('bitmaskd is not running')
        timeout_fun = status_timeout

    try:
        yield cli._send(
            timeout=0.1, printer=_null_printer,
            errb=lambda: timeout_fun(args))
    except Exception, e:
        print(Fore.RED + "ERROR: " + Fore.RESET +
              "%s" % str(e))
        yield reactor.stop() 
Example #14
Source File: ginnoptimizer.py    From galera_innoptimizer with GNU General Public License v2.0 6 votes vote down vote up
def print_color(mtype, message=''):
    """@todo: Docstring for print_text.

    :mtype: set if message is 'ok', 'updated', '+', 'fail' or 'sub'
    :type mtype: str
    :message: the message to be shown to the user
    :type message: str

    """

    init(autoreset=False)
    if (mtype == 'ok'):
        print(Fore.GREEN + 'OK' + Fore.RESET + message)
    elif (mtype == '+'):
        print('[+] ' + message + '...'),
    elif (mtype == 'fail'):
        print(Fore.RED + "\n[!]" + message)
    elif (mtype == 'sub'):
        print(('  -> ' + message).ljust(65, '.')),
    elif (mtype == 'subsub'):
        print("\n    -> " + message + '...'),
    elif (mtype == 'up'):
        print(Fore.CYAN + 'UPDATED') 
Example #15
Source File: CmdInterpreter.py    From Jarvis with MIT License 6 votes vote down vote up
def catch_all_exceptions(do, pass_self=True):
    def try_do(self, s):
        try:
            if pass_self:
                do(self, s)
            else:
                do(s)
        except Exception:
            if self._api.is_spinner_running():
                self.spinner_stop("It seems some error has occured")
            print(
                Fore.RED
                + "Some error occurred, please open an issue on github!")
            print("Here is error:")
            print('')
            traceback.print_exc()
            print(Fore.RESET)
    return try_do 
Example #16
Source File: command.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _error(self, msg):
        print Fore.RED + "[!] %s" % msg + Fore.RESET
        sys.exit(1) 
Example #17
Source File: provider.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _print_domains(self, result):
        for i in result:
            print(Fore.GREEN + i['domain'] + Fore.RESET) 
Example #18
Source File: vpn.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def location_printer(result):
    def pprint(key, value):
        print(Fore.RESET + key.ljust(20) + Fore.GREEN +
              value + Fore.RESET)

    for provider, locations in result.items():
        for loc in locations:
            if 'name' not in loc:
                pprint(provider, "---")
            else:
                location_str = ("[%(country_code)s] %(name)s "
                                "(UTC%(timezone)s %(hemisphere)s)" % loc)
                pprint(provider, location_str) 
Example #19
Source File: mapps.py    From Jarvis with MIT License 5 votes vote down vote up
def search_near(things, city=0):
    if city:
        print("{COLOR}Hold on! I'll show {THINGS} near {CITY}{COLOR_RESET}"
              .format(COLOR=Fore.GREEN, COLOR_RESET=Fore.RESET,
                      THINGS=things, CITY=city))
    else:
        print("{COLOR}Hold on!, I'll show {THINGS} near you{COLOR_RESET}"
              .format(COLOR=Fore.GREEN, COLOR_RESET=Fore.RESET, THINGS=things))
        url = "https://www.google.com/maps/search/{0}/@{1},{2}".format(
            things, get_location()['latitude'], get_location()['longitude'])
    webbrowser.open(url) 
Example #20
Source File: CmdInterpreter.py    From Jarvis with MIT License 5 votes vote down vote up
def say(self, text, color="", speak=True):
        """
        This method give the jarvis the ability to print a text
        and talk when sound is enable.
        :param text: the text to print (or talk)
        :param color: for text - use colorama (https://pypi.org/project/colorama/)
                      e.g. Fore.BLUE
        :param speak: False-, if text shouldn't be spoken even if speech is enabled
        """
        print(color + text + Fore.RESET, flush=True)

        if speak:
            self._jarvis.speak(text) 
Example #21
Source File: CmdInterpreter.py    From Jarvis with MIT License 5 votes vote down vote up
def input(self, prompt="", color=""):
        """
        Get user input
        """
        # we can't use input because for some reason input() and color codes do not work on
        # windows cmd
        sys.stdout.write(color + prompt + Fore.RESET)
        sys.stdout.flush()
        text = sys.stdin.readline()
        # return without newline
        return text.rstrip() 
Example #22
Source File: command.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _check_err(self, stuff, printer):
        obj = json.loads(stuff[0])
        if self.print_json:
            print(json.dumps(obj, indent=2))
        elif not obj['error']:
            if 'result' not in obj:
                print(Fore.RED + 'ERROR: malformed response, expected'
                      ' obj["result"]' + Fore.RESET)
            elif obj['result'] is None:
                print(Fore.RED + 'ERROR: empty response. Check logs.' +
                      Fore.RESET)
            else:
                return printer(obj['result'])
        else:
            print(Fore.RED + 'ERROR: ' + '%s' % obj['error'] + Fore.RESET) 
Example #23
Source File: user.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def active(self, raw_args):
        username = self.cfg.get('bonafide', 'active', default='')
        if not username:
            username = '<none>'
        print(Fore.RESET + 'active'.ljust(10) + Fore.GREEN + username +
              Fore.RESET)
        return defer.succeed(None) 
Example #24
Source File: command.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def print_status(status, depth=0):

    if status.get('vpn') == 'disabled':
        print('vpn       ' + Fore.RED + 'disabled' + Fore.RESET)
        return

    for name, v in [('status', status)] + status['childrenStatus'].items():
        line = Fore.RESET + name.ljust(12)
        if v['status'] in ('on', 'starting'):
            line += Fore.GREEN
        elif v['status'] == 'failed':
            line += Fore.RED
        line += v['status']
        if v.get('error'):
            line += Fore.RED + " (%s)" % v['error']
        line += Fore.RESET
        print(line)

    for k, v in status.items():
        if k in ('status', 'childrenStatus', 'error'):
            continue
        if k == 'up':
            k = '↑↑↑         '
        elif k == 'down':
            k = '↓↓↓         '
        print(Fore.RESET + k.ljust(12) + Fore.CYAN + str(v) + Fore.RESET) 
Example #25
Source File: command.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def default_printer(result, key=None):
    if isinstance(result, (str, unicode)):
        if result in ('OFF', 'OFFLINE', 'ABORTED', 'False'):
            color = Fore.RED
        else:
            color = Fore.GREEN

        print_str = ""
        if key is not None:
            print_str = Fore.RESET + key.ljust(10)
        print_str += color + result + Fore.RESET
        print(print_str)

    elif isinstance(result, list):
        if result and isinstance(result[0], list):
            result = map(lambda l: ' '.join(l), result)
            for item in result:
                default_printer('\t' + item, key)
        else:
            result = ' '.join(result)
            default_printer(result, key)

    elif isinstance(result, dict):
        for key, value in result.items():
            default_printer(value, key)

    else:
        default_printer(str(result), key) 
Example #26
Source File: keys.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _print_key(self, key):
        print(Fore.GREEN)
        print("Uids:       " + ', '.join(key['uids']))
        print("Fingerprint:" + key['fingerprint'])
        print("Length:     " + str(key['length']))
        print("Expiration: " + key['expiry_date'])
        print("Validation: " + key['validation'])
        print("Used:       " + "sig:" +
              str(key['sign_used']) + ", encr:" +
              str(key['encr_used']))
        print("Refreshed:   " + key['refreshed_at'])
        print(Fore.RESET)
        print("")
        print(key['key_data']) 
Example #27
Source File: bitmask_cli.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _print_status(self, status):
        for key, value in status.items():
            color = Fore.GREEN
            if value == 'stopped':
                color = Fore.RED
            print(key.ljust(10) + ': ' + color +
                  value + Fore.RESET) 
Example #28
Source File: bitmask_cli.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _print_version(self, version):
        corever = version['version_core']
        print(Fore.GREEN + 'bitmask_core: ' + Fore.RESET + corever) 
Example #29
Source File: user.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _print_user_list(self, users):
        for u in users:
            color = ""
            if u['authenticated']:
                color = Fore.GREEN
            print(color + u['userid'] + Fore.RESET) 
Example #30
Source File: results.py    From dot2moon with MIT License 5 votes vote down vote up
def detail(self, average, characters):
        if self.post != None:
            for l in self.infos:
                print("Payload: %s" % l)
                print("Average Size: %s bytes" % average) 
                print("Default Size: %s bytes" % self.default_size)
                print("Size: %s bytes" % self.infos[l][0])
                try:
                    print("HTML:\n%s" % self.infos[l][1][:characters])
                except IndexError:
                    pass
                print(Fore.YELLOW)
                print("-"*80)
                print(Fore.RESET)

        else:
            for l in self.infos:
                print("URL: %s" % l)
                print("HTTP code: %s" % self.infos[l][0])
            
                if l == self.infos[l][2]:
                    pass
                else:
                    print("Redirected to: %s" % self.infos[l][2])

                print("Average Size: %s bytes" % average) 
                print("Default Size: %s bytes" % self.default_size)
                print("Size: %s bytes" % self.infos[l][1])
                try:
                    print("HTML:\n%s" % self.infos[l][5][:characters])
                except IndexError:
                    pass
                print(Fore.YELLOW)
                print("-"*80)
                print(Fore.RESET)

    #Funtion that will only show the potential results