Python colorama.Fore 模块,WHITE 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorama.Fore.WHITE。
def ex_print (type, msg, ret):
colorama.init()
# Define color and style constants
c_error = Fore.RED
c_action = Fore.YELLOW
c_ok = Fore.GREEN
c_white = Fore.WHITE
s_br = Style.BRIGHT
s_reset = Style.RESET_ALL
message = {
"error": c_error + s_br,
"action": c_action,
"positive": c_ok + s_br,
"info": c_white + s_br,
"reset": s_reset
}
style = message.get(type, s_reset)
if ret == 0:
print(style + msg, end = "")
else:
print(style + msg)
def display_warning_to_user(self):
""" display warning to user
show user the commands + switches and ask if they
would still like to proceed or not """
user_message = Fore.CYAN + "\nYou are about to run the following commands:"
print(user_message)
for command in self.commands:
print(command)
user_message = Fore.CYAN + "\nOn the following devices:"
print(user_message)
for device in sorted(self.devices.keys()):
print(device)
user_message = Fore.RED + "\nAre you sure you wish to proceed? (y/n) " + Fore.WHITE
user_input = input(user_message)
if user_input.lower() == 'y':
return True
else:
return False
def banner():
print(Style.DIM)
print(' ___________________________')
print(' / /\\')
print(' / sadboyzvone\'s _/ /\\')
print(' / Intel 8080 / \/')
print(' / Assembler /\\')
print('/___________________________/ /')
print('\___________________________\/')
print(' \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\'
+ Style.RESET_ALL + Style.BRIGHT)
print(Fore.WHITE + '\nPowered by ' + Fore.BLUE + 'Pyt'
+ Fore.YELLOW + 'hon' + Fore.WHITE
+ '\ncopyright (C) 2017,Zvonimir Rudinski')
# Print usage @R_352_4045@ion
def load_url(url, timeout):
# Build URL query to email signup page
urlquery = "http://" + url + "/m-users-a-email_list-job-add-email-" + targetEmail + "-source-2.htm"
print_out(Style.BRIGHT + Fore.WHITE + "Sending request to: " + url)
# Build the request
req = urllib.request.Request(
urlquery,
data=None,
headers={
'User-Agent': random.choice(useragents),
'Host': url
}
)
# Send
try:
f = urllib.request.urlopen(req)
print_out(Style.BRIGHT + Fore.GREEN + "Successfully sent!")
f.close()
except urllib.error.URLError as e:
print_out(Style.BRIGHT + Fore.RED + e.reason)
def printBoard(self):
"""
Print board to terminal for debugging
"""
def getItem(item):
if item == Board.BLACK :
return Fore.WHITE + "|" + Fore.BLACK + "O"
elif item == Board.WHITE :
return Fore.WHITE + "|" + Fore.WHITE + "O"
else:
return Fore.WHITE + "| "
def getRow(row):
return "".join(map(getItem,row))
print("\t" + Back.GREEN + " BOARD ")
print("\t" + Back.GREEN + Fore.WHITE + " |0|1|2|3|4|5|6|7")
for i in range(8):
print("\t" + Back.GREEN + Fore.WHITE + "{}{}".format(i,
getRow(self.board[i])))
sys.stdout.write(Style.RESET_ALL)
def printBoard(self, t='live'):
"""
Print board to terminal for debugging
@param string type 'virtual' or 'live'
"""
board = self.board if t == 'live' else self.virtualBoard
print(Back.GREEN + "\t BOARD ")
# Print column titles
head = Back.GREEN + Fore.WHITE + "\t "
for i in range(self.board.shape[0]):
head += '|' + str(i)
print(head)
# Print rows
for i in range(self.board.shape[0]):
print(Back.GREEN + Fore.WHITE + "\t" + str(i) + getRow(board[i]))
print(Style.RESET_ALL)
return
def main():
colorama.init()
# gratuitous use of lambda.
pos = lambda y, x: '\x1b[%d;%dH' % (y, x)
# draw a white border.
print(Back.WHITE, end='')
print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='')
for y in range(MINY, 1+MAXY):
print('%s %s ' % (pos(y, pos(y, MAXX)), end='')
print('%s%s' % (pos(MAXY, end='')
# draw some blinky lights for a while.
for i in range(PASSES):
print('%s%s%s%s%s' % (pos(randint(1+MINY,MAXY-1), randint(1+MINX,MAXX-1)), choice(FORES), choice(BACKS), choice(STYLES), choice(CHARS)), end='')
# put cursor to top,left,and set color to white-on-black with normal brightness.
print('%s%s%s%s' % (pos(MINY, Fore.WHITE, Back.BLACK, Style.norMAL), end='')
def getparam(ser, p_name, p_data):
"""Decode a specific parameter from the serial port."""
printc(Back.RED + p_name, prepend='\n')
for typ in p_data:
schr = ser.read()
if typ == 'h':
printc(c2hex(schr), Fore.GREEN)
elif typ == 'H':
if len(HIGHLIGHT):
HIGHLIGHT.popleft()
HIGHLIGHT.append(c2hex(schr))
printc(c2hex(schr), Fore.BLUE)
elif typ == 'a':
printc(c2ascii(schr) or c2hex(schr), prepend='')
else:
printc(c2hex(schr), Fore.WHITE)
printc(Style.RESET_ALL, prepend='')
def menu():
# Using colour from colorama: https://pypi.python.org/pypi/colorama
# Formatting e.g.: Fore.COLOUR,Back.COLOUR,Style.DIM with e.g. DIM,RED,CYAN,etc.:
print(Fore.BLACK + Back.WHITE + "10cbazbt3 menu:" + Style.RESET_ALL)
print(Fore.YELLOW + Style.DIM + "Main:")
print(" b = Blurb m = Mentions")
print(" r = Reply t = Timeline")
print(" blog = BLOG o = Own blurbs")
print(" pins = PINS")
print("Admin:")
print(" Login = Login menu = show Menu")
print(" logout = logout. sites = my Sites")
print(" exit = Exit")
print(Style.RESET_ALL)
# DEFINE 10C POST INteraCTIONS:
# LOTS OF DUPLICATION HERE!
# Define the 'blurb' (social post) subroutine:
def show_options(require):
#print Back.WHITE + Fore.WHITE + "Module parameters" + Style.RESET_ALL
for line in require:
if require[line][0]["value"] == "":
value = "No value"
else:
value = require[line][0]["value"]
if require[line][0]["required"] == "yes":
if require[line][0]["value"] != "":
print Fore.GREEN+Style.BRIGHT+ "+ " +Style.RESET_ALL+line+ ": " +value
else:
print Fore.RED+Style.BRIGHT+ "- " +Style.RESET_ALL+line+ "(" +Fore.RED+ "is_required" +Style.RESET_ALL+ "):" +value
else:
if require[line][0]["value"] != "":
print Fore.GREEN+Style.BRIGHT+ "+ " +Style.RESET_ALL+line + ": " +value
else:
print Fore.WHITE+Style.BRIGHT+ "* " +Style.RESET_ALL+line + "(" +Fore.GREEN+ "optional" +Style.RESET_ALL+ "):" +value
#print Back.WHITE + Fore.WHITE + "End parameters" + Style.RESET_ALL
def print_and_log(to_print, level='info', logger=None, display=True):
if display:
if level == 'default':
for line in to_print:
print Fore.WHITE + line + '\r'
if level == 'info':
print_info(to_print)
elif level == 'error':
print_error(to_print)
if logger is not None:
write_to_logger(logger, to_print, level)
sys.stdout.flush()
def printHelp():
print('\nThis ' + Fore.BLUE + 'Intel' + Fore.WHITE
+ ' 8080 assembler was made for ' + Fore.BLUE + 'Project '
+ Fore.YELLOW + 'Week' + Fore.WHITE + ' at my school.')
print('It is written in ' + Fore.BLUE + 'Pyt' + Fore.YELLOW + 'hon'
+ Fore.WHITE)
print('Modules: ' + Fore.RED + 'Co' + Fore.BLUE + 'lo'
+ Fore.YELLOW + 'ra' + Fore.GREEN + 'ma' + Fore.WHITE)
print('\nPass a file path as an arguement.')
# Main function
def color_row(row):
color = Fore.WHITE
label = "."
if u'label' in row:
color = LABEL_COLOR.get(row[u'label'], Fore.WHITE)
label = row[u'label']
row[u'label'] = "%s%s%s" % (color, label, Style.RESET_ALL)
row['family'] = "%s%s%s" % (color, row.get('family', "."), Style.RESET_ALL)
row['size'] = smart_size(row.get(u'size', "."))
return row
def m_fatal(self, m):
m = '[X] ' + m
if COLORAMA:
print Fore.WHITE + Back.RED + m
else:
print m
def m_fatal(self, m):
m = '[X] ' + m
if COLORAMA:
print Fore.WHITE + Back.RED + m
else:
print m
def m_fatal(self, m):
m = '[X] ' + m
if COLORAMA:
print Fore.WHITE + Back.RED + m
else:
print m
def print_major_alarms(mj):
"""
Args:
mj (int): Counts of major alarms
Returns:
str: Colorized @R_352_4045@ion 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
def run_plugin( plugin ):
start = time.time()
print '[-] Start {}'.format( plugin[1] )
with open( devnull, 'w' ) as FNULL:
subprocess.call( plugin, stdout=FNULL )
#end = '[+] Ends {0:<20}: {:.2f}s'.format( plugin[1],time.time() - start )
end = '{:.2f}s'.format( time.time() - start )
print (Fore.WHITE + '[+]') , 'Ends {:25}--> {}'.format( plugin[1], end )
return
def present_synonyms(synonym_groups, query):
table = defaultdict(list)
for sg in sorted(synonym_groups.keys()):
synonyms = synonym_groups[sg]
table[sg] = [COLORS[category - 1] + word
for category in sorted(synonyms.keys(), reverse=True)
for word in sorted(synonyms[category])]
table[sg].append(Fore.WHITE + "")
print ">> Results from searching: %s,where the first row denotes the context of where the synonyms are used.\n" % query
print tabulate(table, tablefmt="rst", headers="keys")
def _run(self, marc_record):
print()
time.sleep(1)
print('{}{}: {}{}'.format(Fore.WHITE, marc_record.id, marc_record.title(), Style.RESET_ALL).encode('utf-8'))
for field in marc_record.fields:
if field.tag.startswith('6'):
if field.sf('2') == self.source.sf['2']:
if field.match(self.source):
print(' > {}{}{}'.format(Fore.YELLOW, field, Style.RESET_ALL).encode('utf-8'))
else:
print(' {}{}{}'.format(Fore.YELLOW, Style.RESET_ALL).encode('utf-8'))
else:
print(' {}'.format(field).encode('utf-8'))
while True:
targets = pick('Make a selection (or press Ctrl-C to abort)', self.targets, OrderedDict((
('REMOVE', 'None of them (remove the field)'),
)))
if 'REMOVE' in targets and len(targets) > 1:
log.warning('Invalid selection. Please try again or press Ctrl-C to abort.')
else:
break
if len(targets) == 0:
log.info('Skipping this record')
return 0
tasks = []
if 'REMOVE' in targets:
tasks.append(DeleteTask(self.source, ignore_extra_subfields=self.ignore_extra_subfields))
else:
tasks.append(ReplaceTask(self.source, targets[0], ignore_extra_subfields=self.ignore_extra_subfields))
for target in targets[1:]:
tasks.append(AddTask(target))
modified = 0
for task in tasks:
modified += task.run(marc_record)
return modified
def __str__(self):
return 'List titles having `{}`'.format(Fore.WHITE + six.text_type(self.source) + Style.RESET_ALL)
def __str__(self):
return 'Delete `{}`'.format(Fore.WHITE + six.text_type(self.source) + Style.RESET_ALL)
def __str__(self):
return 'Add `{}`'.format(Fore.WHITE + six.text_type(self.target) + Style.RESET_ALL)
def color_green(text):
return Fore.GREEN+text+Fore.WHITE
# JSON validator function
def screen_data(self, defrag=False):
status = self.status
text = Fore.WHITE
text += term.bold('Pyflix\n\n')
text += STATES[status.state]
text += term.yellow(' %.2f%% complete ' % (status.progress * 100))
rates = self.rates()
rate_text = '(down: %.1f kB/s up: %.1f kB/s peers: %d)\n' % \
(rates[0], rates[1], status.num_peers)
text += term.green(rate_text)
if defrag:
text += self.defrag()
text += Fore.WHITE
text += "\n\n"
if self._video_file is not None:
text += term.white("Serving ")
text += term.yellow(self.video_file[0])
text += term.white(" on ")
text += term.blue("http://localhost:%s\n") % self.port
text += term.white("Elapsed Time: ")
text += term.red(self.elapsed_time())
text += "\n"
return text
def log(text):
print(Fore.GREEN + '==> ' + Fore.WHITE + text)
def log_warn(text):
print(Fore.YELLOW + '==> Warning: ' + Fore.WHITE + text)
def log_err(text):
print(Fore.RED + '==> Error: ' + Fore.WHITE + text)
# NOTE: If you use this script as module,call this function!
def TOR_CHECK_PRNT(data):
if (data["IsTor"]==True):
print ("[" + Fore.GREEN + Style.BRIGHT + "+" + Style.RESET_ALL + "]" + Fore.GREEN + Style.BRIGHT + " TorStat's network traffic was routed through tor,onto the next stage...\n" + Style.RESET_ALL)
return True
elif (data["IsTor"]==False):
print ("[" + Fore.YELLOW + Style.BRIGHT + "!" + Style.RESET_ALL + "]" + Fore.YELLOW + Style.BRIGHT +" TorStat cannot perform any more recon on the tor servers because TorStat's network traffic was not routed through tor.\n\t " + Style.RESET_ALL + Fore.WHITE + Style.DIM + "=> try : proxychains python TorStat.py\n" + Style.RESET_ALL)
return False
def NODE_INFO(IP_ADDR):
resp = urllib2.urlopen("https://onionoo.torproject.org/details?search=%s"%(IP_ADDR))
json_data = resp.read()
data = json.loads(json_data, object_pairs_hook=OrderedDict)
rp = bp = None
colors_lst = [Fore.GREEN + Style.BRIGHT, Fore.RED + Style.BRIGHT, Fore.YELLOW + Style.BRIGHT, Fore.WHITE + Style.BRIGHT, Fore.CYAN + Style.BRIGHT]
for key, value in data.items():
if key == "version" or key == "bridges":
continue
if key == "relays_published":
rp = value
if key == "bridges_published":
bp = value
if key == "relays":
for each in value:
for e_key, e_val in each.items():
#if lists
if e_key == "or_addresses":
print (Fore.GREEN + Style.BRIGHT + e_key.upper() + Fore.WHITE + Style.BRIGHT + " : " + ','.join(e_val))
continue
if e_key.lower() == "exit_policy_summary" or e_key.lower() == "exit_policy" or e_key.lower() == "exit_policy_v6_summary":
continue
if str(e_val).startswith("[") and str(e_val).endswith(']'):
print (Fore.GREEN + Style.BRIGHT + e_key.upper() + Style.RESET_ALL)
for ef in e_val:
print Fore.BLUE + Style.BRIGHT + "\t=> "+ ef + Style.RESET_ALL
continue
try:
print (Fore.GREEN + Style.BRIGHT + e_key.upper().replace('_',' ') + Style.RESET_ALL + " : " + \
Fore.WHITE + Style.BRIGHT + str(e_val))
except: pass
print
if (rp!=None and bp!= None):
print (Fore.GREEN + Style.BRIGHT + "RELAYS PUBLISHED" + Style.RESET_ALL + " : " + Fore.WHITE + Style.BRIGHT + rp)
print (Fore.GREEN + Style.BRIGHT + "BRIDGES PUBLISHED" + Style.RESET_ALL + " : " + Fore.WHITE + Style.BRIGHT + bp)
def parseLine(line):
severity = getSeverity(line)
# Add color based on severity
if 'severity' not in locals():
severity = 3
if severity == 0:
color = Style.DIM + Fore.WHITE
elif severity == 1:
color = Style.norMAL + Fore.BLUE
elif severity == 2:
color = Style.norMAL + Fore.CYAN
elif severity == 3:
color = Style.norMAL + Fore.WHITE
elif severity == 4:
color = Style.norMAL + Fore.RED
elif severity == 5:
color = Style.norMAL + Fore.BLACK + Back.RED
else:
color = Style.norMAL + Fore.BLACK + Back.YELLOW
# Replace html tab entity with actual tabs
line = clearTags(line)
line = line.replace('	', "\t")
return color + line + Style.RESET_ALL
def log(self, message):
print(Fore.WHITE + "[LOG] " + self.timestamp() + " " +
message.encode('ascii', 'ignore').decode('ascii') + Fore.RESET)
return
def getItem(item):
if item == 1:
return Fore.WHITE + "|" + Fore.BLACK + "O"
elif item == 0:
return Fore.WHITE + "| "
else:
return Fore.WHITE + "|" + Fore.WHITE + "O"
def validateBoard(self, t='live'):
'''
Determines if players can still make moves.
If a player cannot move,their turn is automatically skipped.
If neither player can move,the game has ended.
Returns False if the game continues,-1 or 1 if the game has ended.
'''
if self.isGameOver(t):
print("Game Over")
wOwn = self.getownership(self.WHITE)
bOwn = self.getownership(self.BLACK)
if wOwn > bOwn:
print("White wins with", wOwn, "territory to black's", bOwn, ".")
return self.WHITE
else:
print("Black wins with", "territory to white's", ".")
return self.BLACK
nt = self.nextTurn if t == 'live' else self.virtualNextTurn
if not self.canMove(t, nt):
if nt == self.BLACK:
print("Black cannot move,turn passed.")
if t == 'live':
self.nextTurn = self.WHITE
else:
self.virtualNextTurn = self.WHITE
else:
print("White cannot move,turn passed.")
if t == 'live':
self.nextTurn = self.BLACK
else:
self.virtualNextTurn = self.BLACK
return False
def updateBoard(self, t, tile, row, col):
"""
@param string t
either 'virtual' or 'live'
@param int tile
either 1 or -1
1 for player 1 (black)
-1 for player 2 (white)
@param int row
0-7 which row
@param int col
0-7 which col
@return bool
true if valid
false if invalid move - doesn't update board
"""
board = self.board if t == 'live' else self.virtualBoard
result = self.isValidMove(board, col)
if result != False:
if t == 'live' :
self.nextTurn = self.BLACK if self.nextTurn != self.BLACK else self.WHITE
else:
self.virtualNextTurn = self.BLACK if self.virtualNextTurn != self.BLACK else self.WHITE
board[row][col] = tile
for row in result:
board[ row[0] ][ row[1] ] = tile
if ( t == 'live'):
self.syncVirtualBoard()
return True
else:
return False
def __init__(self):
from colorama import init, Fore, Style
init(autoreset=True)
self.colors = {'red': Fore.RED,
'yellow': Fore.YELLOW,
'green': Fore.GREEN,
'white': Fore.WHITE,
'cyan': Fore.CYAN,
'reset': Style.RESET_ALL
}
def writelog(self, message, log_type="info", do_print=True):
"""
Write log file
:param message: Log Text
:param log_type: Log type (info,critical,error,warning,success,catch)
:param do_print: Print to screen
"""
try:
print(Style.RESET_ALL)
message = "[" + time.strftime("%d-%m-%Y %H:%M %s") + "]" + message
if log_type == "critical":
self.l.critical(message)
if do_print:
print(Fore.RED + Style.BRIGHT + message)
elif log_type == "warning":
self.l.warning(message)
if do_print:
print(Fore.YELLOW + message)
elif log_type == "error":
self.l.error(message)
if do_print:
print(Fore.RED + message)
elif log_type == "info":
self.l.info(message)
if do_print:
print(Fore.WHITE + message)
elif log_type == "success":
self.l.info(message)
if do_print:
print(Fore.GREEN + message)
elif log_type == "catch":
self.l.info(message)
if do_print:
print(Fore.BLUE + message)
except Exception as e:
print(str(e))
def FinSaveFile(self):
init(autoreset=True)
OutputFilePath = os.path.abspath(
os.path.join(self.ReadyFilePath, os.pardir)) + "\\"
OutputFileName = OutputFilePath + 'Output_%s.wav' % uuid.uuid4().hex
librosa.output.write_wav(
OutputFileName, self.AfterSignal, self.AfterSignalSR)
print(Back.GREEN + Fore.WHITE + "SAVE DONE" +
Back.BLACK + " Output path -> " + OutputFileName)
logger.info(Back.GREEN + Fore.WHITE + "SAVE DONE" +
Back.BLACK + " Output path -> " + OutputFileName)
def FinSaveFile(self):
init(autoreset=True)
SaveFilePath = self.OutputFilePath
if self.OutputFilePath == '':
SaveFilePath = os.path.abspath(os.path.join(self.ReadyFilePath, os.pardir)) + "\\"
OutputFileName = SaveFilePath + 'Output_%s.wav' % uuid.uuid4().hex
librosa.output.write_wav(SaveFilePath, self.AfterSignalSR)
print(Back.GREEN + Fore.WHITE + "SAVE DONE" + Back.BLACK + " Output path -> " + SaveFilePath)
logger.info("SAVE DONE Output path -> " + SaveFilePath)
def main():
init()
ser = serial.Serial(COM, 19200)
while True:
schr = ser.read()
char = c2ascii(schr)
chx = c2hex(schr)
if char == 'D':
getparam(ser, 'D', 'Haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah')
getparam(ser, '_', 'hhhhahhhhhHhhhhh')
elif char == 'S':
getparam(ser, 'S', 'Hhhhh')
getparam(ser, 'hhhhahhhhhHhhhhh')
elif char == 'R':
getparam(ser, 'R', 'hhhhh')
elif char == 'C':
getparam(ser, 'C', 'hhhhhhhhhh')
elif char == 'B':
getparam(ser, 'B', 'hhh')
#elif char == 'Z':
# getparam(ser,'Z','h')
#elif char == 'W':
# getparam(ser,'W','H')
elif char and ('A' <= char and char <= 'Z' or
'a' <= char and char <= 'z'):
printc(char, prepend = ' ')
else:
printc(chx, Fore.YELLOW)
def _can_continue(self, local_txt, remote_txt, msg):
# Compare text checksum with value in status.json
if self.checksum is None:
return True # it's a new letter
if remote_txt is not None and normalize_line_endings(remote_txt) == normalize_line_endings(local_txt):
self.console_msg(Fore.GREEN + 'no changes' + Style.RESET_ALL)
return False
remote_txt = normalize_line_endings(remote_txt)
remote_chks = [
get_sha1(remote_txt),
get_sha1(remote_txt + "\n"),
]
if self.checksum in remote_chks:
return True
print()
print('\n' + Back.RED + Fore.WHITE + '\n\n Warning: ' + msg % {'local_sha': self.checksum[:8], 'remote_sha': get_sha1(remote_txt)[:8]} + '\n' + Style.RESET_ALL)
msg = 'Continue with {}?'.format(self.filename)
if remote_txt is None:
return input("%s [y: yes,n: no] " % msg).lower()[:1] == 'y'
else:
while True:
response = input(Fore.CYAN + "%s [y: yes,n: no,d: diff] " % msg + Style.RESET_ALL).lower()[:1]
if response == 'd':
show_diff(remote_txt, local_txt)
else:
return response == 'y'
def _wrap_color(code_string):
"""Wrap key parts in styling and resets.
Stying for each key part from,
(col_offset,fromlineno) to (end_col_offset,end_lineno).
Note: use this to set color back to default (on mac,and others?):
Style.RESET_ALL + Style.DIM
"""
ret = Style.BRIGHT + Fore.WHITE + Back.BLACK
ret += code_string
ret += Style.RESET_ALL + Style.DIM + Fore.RESET + Back.RESET
return ret
def authorise():
# Define 'headertokenonly' and 'headers' as global variables,with actual values defined below:
global headertokenonly
global headers
# Define 'headertokenonly' global authentication variable - read from /home/pi/10cv4/authtoken.txt,
# ***The text file MUST exist and contain one line,ONLY the text of the auth token,***
# It's returned from the API at the end of the 'Login' subroutine,
# This header contains only the token - used when only an auth header is required,
# First check if it exists,
# If it does not,ask the user to login for the first time:
try:
open("authtoken.txt")
except IOError as e:
os.system('clear')
print("")
print(Fore.BLACK + Back.WHITE + "10cbazbt3:")
print("")
print(Fore.BLACK + Back.RED + "Please Login for the first time." + Style.RESET_ALL)
print("")
login()
tempinput = input(Fore.YELLOW + "Please press [enter] to continue" + Style.RESET_ALL)
# Then carry on creating the authorisation headers:
authtokenonlyfile = open("authtoken.txt", "r")
authtokenonly = authtokenonlyfile.read()
headertokenonly = {'Authorization': authtokenonly}
# Define the 'headers' global variable using 'authtokenonly' from above,
# This header is used throughout the application:
headers = {'Authorization': authtokenonly, 'Content-Type': 'application/x-www-form-urlencoded'}
# Define the 'login' subroutine:
# Getting and applying the auth token is unnecessarily long,
# Requires less of the file I/O:
def login():
# Input account name:
my_acctname = input(Fore.YELLOW + Style.DIM + "10C Username (account email address): " + Fore.WHITE)
# Input account password:
my_acctpass = getpass.getpass(Fore.YELLOW + Style.DIM + "10C Password (is not shown onscreen): " + Style.RESET_ALL)
# Construct the login URL & data passed to the API:
url = 'https://api.10centuries.org/auth/login'
loginheaders = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {'client_guid': my_client_guid, 'acctname': my_acctname, 'acctpass': my_acctpass}
response = requests.post(url, headers=loginheaders, data=data)
# Saves the server's JSON response to 'loginresponse.txt':
file = open("loginresponse.txt", "w")
file.write(response.text)
file.close()
# Extracts the auth token from the JSON file:
json_data = open("loginresponse.txt", "r")
decoded = json.load(json_data)
temptoken = decoded['data']['token']
# Saves just the auth token to authtoken.txt:
file = open("authtoken.txt", "w")
file.write(temptoken)
file.close()
# Let the user kNow the application is authorised:
print("")
print(Fore.BLACK + Back.GREEN + "Authorised" + Style.RESET_ALL + Fore.YELLOW + Style.DIM + " (but check for a 'Connected' indicator!)" + Style.RESET_ALL)
print("")
setloginstatus("In")
authorise()
# Define the 'logout' subroutine:
def cprint(s, log_level):
colors = {
'debug': (Fore.WHITE,
'info': (Fore.CYAN,
'warning': (Fore.YELLOW, Style.BRIGHT),
'error': (Fore.RED,
'default': (Fore.WHITE, Style.norMAL)
}
color = (colors[log_level] if log_level in colors else colors['default'])
print(color[0], end='')
print(color[1], end='')
print(s)
print(Style.RESET_ALL)
def print_white( str ):
print( Style.BRIGHT + Fore.WHITE + str );
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。