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"
python类RESET的实例源码
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
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")
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
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)
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)
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,
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)
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)
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)
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]
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
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
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
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()
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
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
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
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)
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")
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")
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)
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)
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
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
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)
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")
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
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
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