Python colorama.Fore 模块,RESET 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorama.Fore.RESET

项目:project    作者:swatishayna    | 项目源码 | 文件源码
def read_chat_history():

    choice = select_a_friend()

    if choice is not None:
        print (Fore.BLUE + "Messages sent are shown in blue color \n" + Fore.GREEN + " Received Messages and Read Messages are shown in green color:"+Fore.RESET)

        chats = friends[choice].chats

        for chat in chats:
            if chat.sent_by_me:
                print (Fore.RED + str(chat['time']) + " " + Fore.BLUE + friends[choice]['name'] + " " + Fore.RESET + chat['message'])
            else:
                print (Fore.RED + str(chat['time']) + " " + Fore.GREEN + friends[choice]['name'] + " " + Fore.RESET + chat['message'])
    else:
        print "Wrong choice"
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def option(question, options, default=1):
    print(question)
    options = list(options)
    for idx, element in enumerate(options):
        print("{}) {}".format(idx+1,element))
    while True:
        i = input("{Style.BRIGHT}{Fore.BLUE}:: {Fore.RESET}Please pick[{}]: {Style.RESET_ALL}".format(default, Style=Style, Fore=Fore))
        try:
            if i == "":
                i = default
            else:
                i = int(i)
            if 0 < i <= len(options):
                return options[i-1]
        except:
            pass
    return None
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def play(data):
    if len(data) == 0:
        print(Fore.BLUE + "Song name doesn't exist. (play '"'song name'"') " + Fore.RESET)

    else:
        wanted = data
        find = os.popen("ls | grep -i " + '"' + wanted + '"')
        music = str(find.readline())

        if not music:
            os.system("instantmusic -s " + wanted + " 2> /dev/null")
            find = os.popen("ls -tc --hide='__*' --hide='*.py'")
            music = str(find.readline()).replace("\n", "")
            os.system("XDG_CURRENT_DESKTOP= DESKTOP_SESSION= xdg-open " +
                      music.replace(" ", "\ ").replace(" (", " \("). replace(")", "\)") +
                      " 2> /dev/null")

        else:
            os.system("XDG_CURRENT_DESKTOP= DESKTOP_SESSION= xdg-open " +
                      music.replace(" ", "\ ").replace(" (", " \("). replace(")", "\)") +
                      " 2> /dev/null")
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def live_score(desc):
    mid = match_id(desc)
    data = c.livescore(mid)
    score = {}
    score['matchinfo'] = "{}, {}".format(data['matchinfo']['mnum'], data['matchinfo']['mchdesc'])
    score['status'] = "{}, {}".format(data['matchinfo']['mchstate'].title(), data['matchinfo']['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'] + '\n' + Fore.BLACK

    for scr in reversed(score['batting']['score']):
        text += "{} :- {}/{} in {} overs\n".format(scr['desc'], 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'] + '\n' + Fore.BLACK
    for scr in reversed(score['bowling']['score']):
        text += "{} :- {}/{} in {} overs\n".format(scr['desc'], 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
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def main(self, s):
    # Trims input s to be just the city/region name
    s = s.replace('time ', '').replace('in ', '')

    # Transforms a city name into coordinates using Google Maps API
    loc = getLocation(s)

    # Gets current date and time using TimeZoneDB API
    send_url = (
        "http://api.timezonedb.com/v2/get-time-zone?"
        "key=BFA6XBCZ8AL5&format=json"
        "&by=position&lat={:.6f}&lng={:.6f}".format(*loc)
    )
    r = requests.get(send_url)
    j = json.loads(r.text)
    time = j['formatted']
    self.dst = j['dst']
    # Prints current date and time as YYYY-MM-DD HH:MM:SS
    print(Fore.MAGENTA + "The current date and time in " +
          str(s).title() + " is: " + str(time) + Fore.RESET)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def main(city=0):
    if not city:
        city = getLocation()['city']
    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)
项目:bitmask-dev    作者:leapcode    | 项目源码 | 文件源码
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,
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def get_test_report(self):
        """
        Returns a formatted report which contains information about all tests
        """

        def _short_err_msg(msg):
            if len(msg) > 100:
                msg = "{}...".format(msg[:100])
            msg = msg.replace("\n", " ")
            return msg

        def _make_report_entry(test):
            color = self._color_from_status(test.status)
            err_msg = '({})'.format(_short_err_msg(test.error_message)) if \
                test.error_message else ''
            elapsed = ' ({})'.format(test.elapsed_time) if \
                test.elapsed_time else ''
            return '{} {} {}{}{} {}{}'.format(
                test.pipeline, test.name, color, test.status.upper(),
                elapsed, err_msg, Fore.RESET)

        results = sorted(self._results, key=attrgetter('pipeline'))
        entries = (_make_report_entry(t) for t in results)
        return center_text_message('TESTS SUMMARY') + '\n' + '\n'.join(entries)
项目:ggmt    作者:Granitosaurus    | 项目源码 | 文件源码
def tick(game, template, is_json, no_color):
    if not game:
        raise click.BadParameter('Missing required parameter "game"')

    matches = download_history(game)
    if is_json:
        click.echo(json.dumps(list(matches), indent=2, sort_keys=True))
        return
    template = template if template else DEFAULT_TEMPLATE_RECAP
    template = Template(template)
    for m in matches:
        if no_color or not COLOR_ENABLED:  # if color is disabled just stdout
            print_match(m, template)
            continue
        if m['t1_score'] > m['t2_score']:
            m['t1'] = Fore.GREEN + m['t1'] + Fore.RESET
            m['t2'] = Fore.RED + m['t2'] + Fore.RESET
        else:
            m['t2'] = Fore.GREEN + m['t2'] + Fore.RESET
            m['t1'] = Fore.RED + m['t1'] + Fore.RESET
        print_match(m, template)
项目:torefl    作者:hl037    | 项目源码 | 文件源码
def createEntry(name, pdf_path, comment, bibtex):
    bib = ''.join(bibtex)
    #Todo Catch exceptions
    try:
        db = bibtexparser.loads(bib)
        if db.entries:
            parsedBib = db.entries[0]
        else:
            print(_F.RED, 'No citation for ', name, _F.RESET, sep='')
            parsedBib = None
    except Exception as e:
        print('EX :', e.__class__.__name__)
        print(e)
        parsedBib = None
    comment, tag_list, priority = parseComment(comment)
    return Entry(name, parsedBib, tag_list, priority, None, url=pdf_path, comment=comment)
项目:sec_ai    作者:sboaseter    | 项目源码 | 文件源码
def fetch_missing_ids(self):
        #Twitternames wihout known id's
        swoid = [s.name for s in self.sources if s.id_str == None]
        if len(swoid) == 0: return
        user_lookups = self.api.lookup_users(screen_names=swoid)
#       print('user_lookups response:\n{}'.format(user_lookups))

        user_ids = dict([(u.screen_name, u.id_str) for u in user_lookups])
        for k,v in user_ids.items():
            sdb_id = [s.id for s in self.sources if s.name == k.lower()]
            loggit('\nSource Id: {}'.format(sdb_id))
            sdb = Source.query.get(sdb_id)
            sdb.id_str = v
            loggit('\nUpdated: {} with twitter_id: {}{}{}'.format(k, Fore.GREEN, v, Fore.RESET).encode("utf8"))
        #Store to DB
        db.flush()
        #update twitter_user_ids array

        # Refresh id's and screen_names globally
        db.expire_all()
        self.sources = Source.query.all()
        global twitter_user_ids
        global twitter_screen_names
        twitter_user_ids = [s.id_str for s in self.sources if s.id_str != None]
        twitter_screen_names = [s.name.lower() for s in self.sources if s.id_str != None]
项目:GPArrayController    作者:eastpiger    | 项目源码 | 文件源码
def command(self, command, value=None):
        func_str = 'GoProHero.command({}, {})'.format(command, value)

        if command in self.commandMaxtrix:
            args = self.commandMaxtrix[command]
            # accept both None and '' for commands without a value
            if value == '':
                value = None
            # for commands with values, translate the value
            if value is not None and value in args['translate']:
                value = args['translate'][value]
            # build the final url
            url = self._commandURL(args['cmd'], value)

            # attempt to contact the camera
            try:
                urlopen(url, timeout=self.timeout).read()
                logging.info('{} - http success!'.format(func_str))
                return True
            except (HTTPError, URLError, socket.timeout) as e:
                logging.warning('{}{} - error opening {}: {}{}'.format(
                    Fore.YELLOW, func_str, url, e, Fore.RESET))

        # catchall return statement
        return False
项目:pythonSpider    作者:sheldon9527    | 项目源码 | 文件源码
def trains(self):
        for raw_train in self.available_trains:
            raw_train = raw_train['queryLeftNewDTO']
            train_no = raw_train['station_train_code']
            initial = train_no[0].lower()
            if not self.options or initial in self.options:
                train = [
                    train_no,
                    '\n'.join([Fore.GREEN + raw_train['from_station_name'] + Fore.RESET,
                               Fore.RED + raw_train['to_station_name'] + Fore.RESET]),
                    '\n'.join([Fore.GREEN + raw_train['start_time'] + Fore.RESET,
                               Fore.RED + raw_train['arrive_time'] + Fore.RESET]),
                    self._get_duration(raw_train),
                    raw_train['zy_num'],
                    raw_train['ze_num'],
                    raw_train['rw_num'],
                    raw_train['yw_num'],
                    raw_train['yz_num'],
                    raw_train['wz_num'],
                ]
                yield train
项目:NetZapper    作者:NetZapper    | 项目源码 | 文件源码
def Brute_Thread(ip,username,passwd):
    ssh=paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    global n,flag,flag1
    n=n+1
    try:
        ssh.connect(ip,username=username,password=passwd)
    except paramiko.AuthenticationException:
        print Fore.RED+"[-]Username: %s\tPassword: %s failed."%(username,passwd) + Fore.RESET
    else:
        print Fore.GREEN+"\n********************************************************"       
        print "[#]Username: %s\tPassword: %s Found........!!!"%(username,passwd)
        print "********************************************************"+Fore.RESET
        flag=1
        flag1=1
        print Fore.RED+"\nFound correct password after %s attempts..." %n  +Fore.RESET
        return
    ssh.close()
    return
项目:NetZapper    作者:NetZapper    | 项目源码 | 文件源码
def ready_Dict(ip,username,filename):
    global flag,n
    f=open(filename,"r")
    st=f.read()
    wordlist=st.split('\n')
    for i in wordlist:
        if flag==0:
            t=threading.Thread(Brute_Thread(ip,username,i))
            t.start()
        elif flag==1:
            flag=0
            break
    if flag==1:
        print Fore.RED+"\nFinished wordlist...%s words checked...password not found!!!" % n+Fore.RESET
    n=0
    f.close()
项目:blacklion    作者:Foohx    | 项目源码 | 文件源码
def log(self, prefix, text, line=False):
        now = datetime.now()
        message = ""
        if prefix == '?':
            c = Fore.CYAN
        elif prefix == '+':
            c = Fore.GREEN
        elif prefix == '-':
            c = Fore.RED
        elif prefix == '!':
            c = Fore.YELLOW
        c = Style.BRIGHT + c
        e = Style.RESET_ALL + Fore.RESET
        if line:
            print c+"["+now.strftime("%Y-%m-%d %H:%M:%S")+"]["+prefix+"] "+text+e
        else :
            print "["+now.strftime("%Y-%m-%d %H:%M:%S")+"]["+c+prefix+e+"] "+text
项目:blacklion    作者:Foohx    | 项目源码 | 文件源码
def log(prefix, text, line=False):
    now = datetime.now()
    message = ""
    if prefix == '?':
        c = Fore.CYAN
    elif prefix == '+':
        c = Fore.GREEN
    elif prefix == '-':
        c = Fore.RED
    elif prefix == '!':
        c = Fore.YELLOW
    c = Style.BRIGHT + c
    e = Style.RESET_ALL + Fore.RESET
    if line:
        print c+"["+now.strftime("%Y-%m-%d %H:%M")+"]["+prefix+"] "+text+e
    else :
        print "["+now.strftime("%Y-%m-%d %H:%M")+"]["+c+prefix+e+"] "+text
项目:Python-searchStations    作者:single-pedestrian    | 项目源码 | 文件源码
def trains(self):
        for raw_train in self.available_trains:
            raw_train = raw_train['queryLeftNewDTO']
            train_no = raw_train['station_train_code']
            initial = train_no[0].lower()
            if not self.options or initial in self.options:
                train = [
                    train_no,
                    '\n'.join([Fore.GREEN + raw_train['from_station_name'] + Fore.RESET,
                               Fore.RED + raw_train['to_station_name'] + Fore.RESET]),
                    '\n'.join([Fore.GREEN + raw_train['start_time'] + Fore.RESET,
                               Fore.RED + raw_train['arrive_time'] + Fore.RESET]),
                    self._get_duration(raw_train),
                    raw_train['zy_num'],
                    raw_train['ze_num'],
                    raw_train['rw_num'],
                    raw_train['yw_num'],
                    raw_train['yz_num'],
                    raw_train['wz_num'],
                ]
                yield train
项目:Nuts    作者:HSRNetwork    | 项目源码 | 文件源码
def compare_minion(self, test_case, minion):
        actual_result = test_case.extract_actual_result()
        if minion in actual_result:
            if self._compare_type(test_case.expected_result, actual_result[minion]):
                if test_case.operator == '=':
                    compare = self.comp(test_case.expected_result, actual_result[minion])
                elif test_case.operator == '<':
                    compare = test_case.expected_result < actual_result[minion]
                elif test_case.operator == '>':
                    compare = test_case.expected_result > actual_result[minion]
                elif test_case.operator == 'not':
                    compare = test_case.expected_result != actual_result[minion]
            else:
                self.test_report_logger.warning('%s%s: Result type mismatch ---------%s', Fore.RED, test_case.name,
                                                Fore.RESET)
                compare = False
            result = actual_result[minion]
        else:
            compare = False
            result = None
        return EvaluationResult(minion, result, compare)
项目:spotifyripper-gui    作者:mrhysjones    | 项目源码 | 文件源码
def create_playlist_m3u(self, tracks):
        args = self.args
        ripper = self.ripper

        name = self.get_playlist_name()
        if name is not None and args.playlist_m3u:
            name = sanitize_playlist_name(to_ascii(name))
            _base_dir = base_dir()
            playlist_path = to_ascii(
                os.path.join(_base_dir, name + '.m3u'))

            print(Fore.GREEN + "Creating playlist m3u file " +
                  playlist_path + Fore.RESET)

            encoding = "ascii" if args.ascii else "utf-8"
            with codecs.open(enc_str(playlist_path), 'w', encoding) as playlist:
                for idx, track in enumerate(tracks):
                    track.load()
                    if track.is_local:
                        continue
                    _file = ripper.format_track_path(idx, track)
                    if path_exists(_file):
                        playlist.write(os.path.relpath(_file, _base_dir) +
                                       "\n")
项目:spotifyripper-gui    作者:mrhysjones    | 项目源码 | 文件源码
def clean_up_partial(self):
        ripper = self.ripper

        if ripper.audio_file is not None and path_exists(ripper.audio_file):
            print(Fore.YELLOW + "Deleting partially ripped file" + Fore.RESET)
            rm_file(ripper.audio_file)

            # check for any extra pcm or wav files
            def delete_extra_file(ext):
                audio_file = change_file_extension(ripper.audio_file, ext)
                if path_exists(audio_file):
                    rm_file(audio_file)

            if self.args.plus_wav:
                delete_extra_file("wav")

            if self.args.plus_pcm:
                delete_extra_file("pcm")
项目:spotifyripper-gui    作者:mrhysjones    | 项目源码 | 文件源码
def queue_remove_from_playlist(self, idx):
        ripper = self.ripper

        if self.args.remove_from_playlist:
            if ripper.current_playlist:
                if ripper.current_playlist.owner.canonical_name == \
                        ripper.session.user.canonical_name:
                    self.tracks_to_remove.append(idx)
                else:
                    print(Fore.RED +
                          "This track will not be removed from playlist " +
                          ripper.current_playlist.name + " since " +
                          ripper.session.user.canonical_name +
                          " is not the playlist owner..." + Fore.RESET)
            else:
                print(Fore.RED +
                      "No playlist specified to remove this track from. " +
                      "Did you use '-r' without a playlist link?" + Fore.RESET)
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
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)
项目:12306    作者:lexyhp    | 项目源码 | 文件源码
def trains(self):
        for raw_train in self.available_trains:
            raw_train_list = raw_train.split('|')
            train_no = raw_train_list[3]
            initial = train_no[0].lower()
            duration = raw_train_list[10]
            if initial in self.options:
                train = [
                    train_no,
                    '\n'.join([Fore.LIGHTGREEN_EX + self.available_place[raw_train_list[6]] + Fore.RESET,
                               Fore.LIGHTRED_EX + self.available_place[raw_train_list[7]] + Fore.RESET]),
                    '\n'.join([Fore.LIGHTGREEN_EX + raw_train_list[8] + Fore.RESET,
                               Fore.LIGHTRED_EX + raw_train_list[9] + Fore.RESET]),
                    duration,
                    raw_train_list[-4] if raw_train_list[-4] else '--',
                    raw_train_list[-5] if raw_train_list[-5] else '--',
                    raw_train_list[-14] if raw_train_list[-14] else '--',
                    raw_train_list[-12] if raw_train_list[-12] else '--',
                    raw_train_list[-7] if raw_train_list[-7] else '--',
                    raw_train_list[-6] if raw_train_list[-6] else '--',
                    raw_train_list[-9] if raw_train_list[-9] else '--',
                ]
                yield train
项目:tickets    作者:Jimzjy    | 项目源码 | 文件源码
def trains(self):
        for raw_train in self.available_trains:
            train_no = raw_train['queryLeftNewDTO']['station_train_code']
            initial = train_no[0].lower()
            if not self.options or initial in self.options:
                train = [
                    train_no,
                    '\n'.join([Fore.GREEN + raw_train['queryLeftNewDTO']['from_station_name'] + Fore.RESET,
                              Fore.RED + raw_train['queryLeftNewDTO']['to_station_name'] + Fore.RESET]),
                    '\n'.join([Fore.GREEN + raw_train['queryLeftNewDTO']['start_time'] + Fore.RESET,
                              Fore.RED + raw_train['queryLeftNewDTO']['arrive_time'] + Fore.RESET]),
                    self._get_duration(raw_train),
                    raw_train['queryLeftNewDTO']['zy_num'],
                    raw_train['queryLeftNewDTO']['ze_num'],
                    raw_train['queryLeftNewDTO']['rw_num'],
                    raw_train['queryLeftNewDTO']['yw_num'],
                    raw_train['queryLeftNewDTO']['yz_num'],
                    raw_train['queryLeftNewDTO']['wz_num'],
                ]
                yield train
项目:spotify-ripper    作者:hbashton    | 项目源码 | 文件源码
def queue_remove_from_playlist(self, idx):
        ripper = self.ripper

        if self.args.remove_from_playlist:
            if ripper.current_playlist:
                if ripper.current_playlist.owner.canonical_name == \
                        ripper.session.user.canonical_name:
                    self.tracks_to_remove.append(idx)
                else:
                    print(Fore.RED +
                          "This track will not be removed from playlist " +
                          ripper.current_playlist.name + " since " +
                          ripper.session.user.canonical_name +
                          " is not the playlist owner..." + Fore.RESET)
            else:
                print(Fore.RED +
                      "No playlist specified to remove this track from. " +
                      "Did you use '-r' without a playlist link?" + Fore.RESET)
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def yes_no(question, default="yes"):
    """Ask a yes/no question via input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True,
             "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(Style.BRIGHT + Fore.BLUE + ":: " + Fore.RESET + question + prompt + Style.NORMAL)
        choice = input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")
项目:githubutils    作者:jimzucker    | 项目源码 | 文件源码
def printIt( p, sha, type, repo, branch, login, message, filler):

    #clean up comments that have \n in them
    message = message.replace("\n"," ")

    #print Fore.RED+sha[:SHACOLW].ljust(SHACOLW," ")+Fore.RESET,type[:EVENTCOLW].ljust(EVENTCOLW,filler),repo[:DFLTCOLW].ljust(DFLTCOLW,filler),branch[:BRANCHCOLW].ljust(BRANCHCOLW,filler),Fore.BLUE+login.ljust(DFLTCOLW," ")+Fore.RESET,message.ljust(MSGCOLW," ")
    line = Fore.RED+sha[:SHACOLW].ljust(SHACOLW," ")+Fore.RESET
    line += " " + type[:EVENTCOLW].ljust(EVENTCOLW,filler)
    line += " " + repo[:DFLTCOLW].ljust(DFLTCOLW,filler)
    line += " " + branch[:BRANCHCOLW].ljust(BRANCHCOLW,filler)
    line += " " + Fore.BLUE+login.ljust(DFLTCOLW," ")+Fore.RESET
    line += " " + message.ljust(MSGCOLW," ")
    line += "\n"

    try:
        p.stdin.write(line)
    except:
        # Stop loop on "Invalid pipe" or "Invalid argument".
        # No sense in continuing with broken pipe.
        exit(1)

    return


#----------------------------------------------------------------------------------------------------------------------

#process arguments
项目:pythonVSCode    作者:DonJayamanne    | 项目源码 | 文件源码
def print_to_stdout(level, str_out):
    """ The default debug function """
    if level == NOTICE:
        col = Fore.GREEN
    elif level == WARNING:
        col = Fore.RED
    else:
        col = Fore.YELLOW
    if not is_py3:
        str_out = str_out.encode(encoding, 'replace')
    print(col + str_out + Fore.RESET)


# debug_function = print_to_stdout
项目:pythonVSCode    作者:DonJayamanne    | 项目源码 | 文件源码
def print_to_stdout(color, str_out):
    """
    The default debug function that prints to standard out.

    :param str color: A string that is an attribute of ``colorama.Fore``.
    """
    col = getattr(Fore, color)
    _lazy_colorama_init()
    if not is_py3:
        str_out = str_out.encode(encoding, 'replace')
    print(col + str_out + Fore.RESET)


# debug_function = print_to_stdout
项目:xmlrpc-bruteforcer    作者:AresS31    | 项目源码 | 文件源码
def copyright():

    copyright = """
       =[ {0}smali-code-injector v1.1-dev{1}       ]
+ -- --=[ Alexandre Teyar @Ares              ]
+ -- --=[ Pentester at Ambersail Ltd.        ]
+ -- --=[ GitHub: https://github.com/AresS31 ]
""".format(Fore.YELLOW, Fore.RESET)
    print("{}".format(copyright))
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def load_plugins(self):
        logger = logging.getLogger(__name__)
        if not os.path.isdir(plugin_dir):
            return
        possible_plugins = os.listdir(plugin_dir)
        for filename in possible_plugins:
            if not os.path.isfile(os.path.join(plugin_dir, filename)):
                continue
            split = filename.split('.')
            if not (len(split) > 1 and split[-1] == "py"):
                continue
            name = "".join(split[:-1])
            module_info = imp.find_module(name, [plugin_dir])
            try:
                module = imp.load_module(name, *module_info)
                dir_list = dir(module)
                if ("get_label" in dir_list) and ("run_command" in dir_list):
                    self.plugins.append(module)
                else:
                    logger.error(Fore.RED + "'%s' is not a valid plugin!" + Fore.RESET, filename)
            except Exception as e:
                logger.error(Fore.RED + "%s error while loading plugin '%s': \n %s" + Fore.RESET,
                             type(e).__name__, filename, e)
            finally:
                module_info[0].close()

    # Return a list of loaded plugins
项目:python-ossi    作者:iskhomutov    | 项目源码 | 文件源码
def print_major_alarms(mj):
    """
    Args:
        mj (int): Counts of major alarms

    Returns:
        str: Colorized information by using colorama
    """
    if mj > 0:
        return Back.RED + Fore.WHITE + str(mj) + Fore.RESET + Back.RESET
    else:
        return Fore.GREEN + str(mj) + Fore.RESET
项目:python-ossi    作者:iskhomutov    | 项目源码 | 文件源码
def print_minor_alarms(mn):
    """
    Args:
        mn (int): Counts of minor alarms

    Returns:
        str: Colorized information by using colorama
    """
    if mn > 0:
        return Fore.RED + str(mn) + Fore.RESET
    else:
        return Fore.GREEN + str(mn) + Fore.RESET
项目:python-ossi    作者:iskhomutov    | 项目源码 | 文件源码
def print_warnings(wn):
    """
    Args:
        wn (int): Counts of warnings

    Returns:
        str: Colorized information by using colorama
    """
    if wn > 0:
        return Fore.YELLOW + str(wn) + Fore.RESET
    else:
        return Fore.GREEN + str(wn) + Fore.RESET
项目:ARPySnitch    作者:securecurebt5    | 项目源码 | 文件源码
def run(self):
        try:
            arp_header = struct.unpack('!2s2s1s1s2s6s4s6s4s', self.arpdata[14:42])
            if hexlify(arp_header[4]) == "0002" and hexlify(arp_header[5]) != self.GW_MAC.replace(":","") and socket.inet_ntoa(arp_header[6]) == self.GW_IP:
                try:
                   if hexlify(arp_header[5]) not in Attacker:
                    Attacker.append(hexlify(arp_header[5]))
                    print "="*50 
                    print foreground.RED + "ARP Poison Detected" + foreground.RESET
                    print "="*50 
                    print "******************_ARP_HEADER_******************"
                    print "Hardware Type: ", hexlify(arp_header[0])
                    print "Protocol Type: ", hexlify(arp_header[1])
                    print "Hardware Size: ", hexlify(arp_header[2])
                    print "Protocol Size: ", hexlify(arp_header[3])
                    print "Opcode: ", opcodes[hexlify(arp_header[4])]
                    print "Attacker's MAC : ", foreground.RED + hexlify(arp_header[5]) + foreground.RESET
                    print "Source IP : ", socket.inet_ntoa(arp_header[6])
                    print "Destination MAC : ", hexlify(arp_header[7])
                    print "Destination IP : ", socket.inet_ntoa(arp_header[8])
                   else:
                    pass
                except:
                    pass
        except:
                pass
项目:TyStrings    作者:luckytianyiyan    | 项目源码 | 文件源码
def success(self, msg, *args, **kwargs):
        self._log(SUCCESS, BEERS_EMOJI + ' ' + Fore.LIGHTWHITE_EX + msg + Fore.RESET, args, **kwargs)
项目:TyStrings    作者:luckytianyiyan    | 项目源码 | 文件源码
def addition(self, msg, *args, **kwargs):
        self._log(ADDITION, BEERS_EMOJI + ' ' + Fore.LIGHTWHITE_EX + msg + Fore.RESET, args, **kwargs)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def do_match(self, s):
        """Matches patterns in a string by using regex."""
        if six.PY2:
            file_name = raw_input(Fore.RED + "Enter file name?:\n" + Fore.RESET)
            pattern = raw_input(Fore.GREEN + "Enter string:\n" + Fore.RESET)
        else:
            file_name = input(Fore.RED + "Enter file name?:\n" + Fore.RESET)
            pattern = input(Fore.GREEN + "Enter string:\n" + Fore.RESET)
        file_name = file_name.strip()
        if file_name == "":
            print("Invalid Filename")
        else:
            system("grep '" + pattern + "' " + file_name)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def do_movies(self, s):
        """Jarvis will find a good movie for you."""
        if six.PY2:
            movie_name = raw_input(
                Fore.RED + "What do you want to watch?\n" + Fore.RESET)
        else:
            movie_name = input(
                Fore.RED + "What do you want to watch?\n" + Fore.RESET)
        system("ims " + movie_name)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def postcmd(self, stop, line):
        """Hook that executes after every command."""
        if self.first_reaction:
            self.prompt = (
                Fore.RED +
                "{} What can i do for you?\n".format(PROMPT_CHAR) + Fore.RESET
            )
            self.first_reaction = False
        if self.enable_voice:
            self.speech.text_to_speech("What can i do for you?\n")
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def test_calc(self):
        # Test a basic calculation
        calc("2 powER 7 PLUS (6.7 Minus 3) diVided BY 0.45 bY 3", self.jarvis)
        sys.stdout.seek(0)
        output = sys.stdout.read().strip()
        result = Fore.BLUE + str(2 ** 7 + (6.7 - 3) / 0.45 / 3) + Fore.RESET
        self.assertEqual(output, result)

        # And now for something a little more _complex_
        sys.stdout = StringIO()
        calc("(1 pluS 9.1j)^3.14129 mINUS 2.712", self.jarvis)
        sys.stdout.seek(0)
        output = sys.stdout.read().strip()
        result = Fore.BLUE + str((1 + 9.1j)**3.14129 - 2.712) + Fore.RESET
        self.assertEqual(output, result)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def read_file(name, default=None):
    if os.path.exists(name):
        try:
            with open(name, "r+") as f:
                return json.load(f)
        except ValueError:
            print(
                Fore.RED + "Storage file not in right format. Backup stored as {0}.bak".format(name) + Fore.RESET)
            os.rename(name, name + ".bak")
    return default
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def print_after(path):
    print(Fore.LIGHTBLUE_EX + "\nFolders after cleaning\n" + Fore.RESET)

    for files in os.listdir(path):
        print(files, sep=',\t')

    print(Fore.LIGHTMAGENTA_EX + "\nCLEANED\n" + Fore.RESET)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def commentary(desc):
    mid = match_id(desc)
    data = c.commentary(mid)
    comm = {}
    comm['matchinfo'] = "{}, {}".format(data['matchinfo']['mnum'], data['matchinfo']['mchdesc'])
    comm['status'] = "{}, {}".format(data['matchinfo']['mchstate'].title(), data['matchinfo']['status'])
    comm['commentary'] = data['commentary']
    text = ''
    text += Fore.LIGHTYELLOW_EX + comm['matchinfo'] + '\n' + comm['status'] + '\n\n' + Fore.RESET
    for com in comm['commentary']:
        text += "{}\n\n".format(com)

    return text
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def locate_me():
    hcity = get_location()['city']
    print(Fore.BLUE + "You are at " + hcity + Fore.RESET)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def weather(city=None):
    if not city:
        city = get_location()['city']

    # Checks country
    country = get_location()['country_name']

    # If country is US, shows weather in Fahrenheit
    if country == 'United States':
        send_url = (
            "http://api.openweathermap.org/data/2.5/weather?q={0}"
            "&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=imperial".format(
                city)
        )
        unit = ' ºF in '

    # If country is not US, shows weather in Celsius
    else:
        send_url = (
            "http://api.openweathermap.org/data/2.5/weather?q={0}"
            "&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=metric".format(
                city)
        )
        unit = ' ºC in '
    r = requests.get(send_url)
    j = json.loads(r.text)

    # check if the city entered is not found
    if 'message' in j and j['message'] == 'city not found':
        print(Fore.BLUE + "City Not Found" + Fore.RESET)
        return False

    else:
        temperature = j['main']['temp']
        description = j['weather'][0]['main']
        print(Fore.BLUE + "It's " + str(temperature) + unit +
              str(city) + " (" + str(description) + ")" + Fore.RESET)

    return True
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def search_near(things, city=0):
    if city:
        print(Fore.GREEN + "Hold on!, I'll show " + things +
              " near " + city + Fore.RESET)
        url = "https://www.google.com/maps/search/{0}+{1}".format(things, city)
    else:
        print(Fore.GREEN + "Hold on!, I'll show " +
              things + " near you" + Fore.RESET)
        url = "https://www.google.com/maps/search/{0}/@{1},{2}".format(
            things, get_location()['latitude'], get_location()['longitude'])
    webbrowser.open(url)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def main(self, s):
    # Trim input command to get only the location
    loc = s.replace('weather', '').replace('in ', '').strip()

    # Checks country
    country = mapps.get_location()['country_name']

    # If country is US, shows weather in Fahrenheit
    if country == 'United States':
        send_url = (
            "http://api.openweathermap.org/data/2.5/weather?q={0}"
            "&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=imperial".format(
                loc)
        )
        unit = ' ºF in '

    # If country is not US, shows weather in Celsius
    else:
        send_url = (
            "http://api.openweathermap.org/data/2.5/weather?q={0}"
            "&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=metric".format(loc)
        )
        unit = ' ºC in '
    r = requests.get(send_url)
    j = json.loads(r.text)

    if 'message' in list(j.keys()) and ('city not found' in j['message'] or 'Nothing to geocode' in j['message']):
        return pinpoint.main(Memory(), self, s)

    temperature = j['main']['temp']
    description = j['weather'][0]['main']
    location = j['name']
    print(Fore.BLUE + "It's " + str(temperature) + unit +
          str(location.title()) + " (" + str(description) + ")" + Fore.RESET)
项目:Jarvis    作者:sukeesh    | 项目源码 | 文件源码
def critical(string):
    print(Fore.RED + string + Fore.RESET)