Python源码示例:colorama.Style.RESET_ALL
示例1
def get_subreddits(self, parser, reddit):
subreddit_prompt = Style.BRIGHT + """
Enter Subreddit or a list of Subreddits (separated by a space) to scrape:
""" + Style.RESET_ALL
while True:
try:
search_for = str(input(subreddit_prompt))
if not search_for:
raise ValueError
return PrintSubs().print_subreddits(parser, reddit, search_for)
except ValueError:
print("No Subreddits were specified! Try again.")
### Update Subreddit settings in master dictionary.
示例2
def get_settings(self, master, subs):
for sub in subs:
while True:
try:
cat_i = int(input((Style.BRIGHT + """
Select a category to display for r/%s
-------------------
0: Hot
1: New
2: Controversial
3: Top
4: Rising
5: Search
-------------------
""" + Style.RESET_ALL) % sub))
if cat_i == 5:
print("\nSelected search")
self._get_search(cat_i, master, sub)
else:
print("\nSelected category: %s" % self._categories[cat_i])
self._get_n_results(cat_i, master, sub)
break
except (IndexError, ValueError):
print("Not an option! Try again.")
示例3
def _colorize(self, text):
palette = PALETTES[self.palette]
palette_reverse = PALETTES_REVERSE[self.palette]
def _colorize_curlies_block(text):
text = text.group()[1:-1]
stripped = text.lstrip('0123456789-')
color_number = int(text[:len(text)-len(stripped)])
reverse = False
if color_number < 0:
color_number = -color_number
reverse = True
if reverse:
stripped = palette_reverse[color_number] + stripped + Style.RESET_ALL
else:
stripped = palette[color_number] + stripped + Style.RESET_ALL
return stripped
return re.sub("{.*?}", _colorize_curlies_block, text)
示例4
def exe(cmd, params):
"""This function runs after preprocessing of code. It actually executes commands with subprocess
:param cmd: command to be executed with subprocess
:param params: parameters passed before ` character, i.e. p`echo 1 which means print result of execution
:return: result of execution. It may be either Result or InteractiveResult
"""
global _colorama_intialized
if _is_colorama_enabled() and not _colorama_intialized:
_colorama_intialized = True
colorama.init()
if config.PRINT_ALL_COMMANDS:
if _is_colorama_enabled():
_print_stdout(Fore.GREEN + '>>> ' + cmd + Style.RESET_ALL)
else:
_print_stdout('>>> ' + cmd)
if _is_param_set(params, _PARAM_INTERACTIVE):
return _create_interactive_result(cmd, params)
else:
return _create_result(cmd, params)
示例5
def sreadline(self):
line = self._file.readline()
if sys.version_info[0] == 3:
line = line.decode(self._encoding)
if line == '':
raise StopIteration
else:
line = line.rstrip(os.linesep)
if self._print_out_stream:
if self._color is None:
_print_stdout(line)
else:
_print_stdout(self._color + line + Style.RESET_ALL)
return line
示例6
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"
示例7
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)
示例8
def __init__(self):
self.Q = read_questions()
self.answers = {}
self.instruction = Back.YELLOW + "There are a total of " +\
"32 pairs of descriptions. For each pair, choose on a scale of " +\
"1-5. Choose 1 if you are all the way to the left, and choose " +\
"3 if you are in the middle, etc." + Style.RESET_ALL
self.types = ['IE', 'SN', 'FT', 'JP']
self.scoring_scheme = ((30, (15, 23, 27), (3, 7, 11, 19, 31)),
(12, (4, 8, 12, 16, 20, 32), (24, 28)),
(30, (6, 10, 22), (2, 14, 18, 26, 30)),
(18, (1, 5, 13, 21, 29), (9, 17, 25)))
self.scores = []
self.type = []
示例9
def print_body_state(self, jarvis, bmi):
"""
According the bmi number, print_body_state finds out the state of the body
and prints it to the user using colorama library for some coloring
"""
print("BMI:", str(bmi))
if bmi < 16:
print(Back.RED, " " * 2, Style.RESET_ALL)
jarvis.say('Severe thinness')
elif bmi < 18.5:
print(Back.YELLOW, " " * 2, Style.RESET_ALL)
jarvis.say('Mild thinness')
elif bmi < 25:
print(Back.GREEN, " " * 2, Style.RESET_ALL)
jarvis.say('Healthy')
elif bmi < 30:
print(Back.YELLOW, " " * 2, Style.RESET_ALL)
jarvis.say('Pre-obese')
else:
print(Back.RED, " " * 2, Style.RESET_ALL)
jarvis.say('Obese')
示例10
def check_names(infile): #Checking the path to the wordlist
if os.path.exists(infile):
if status_method:
banner() #calls the banner function
checkasciiwolf() #calls the sexy ASCII wolf wallpaper
scan_start()
statusfindAdmin() #calls the function that basically does the job
print(Fore.RED + Style.BRIGHT + "\n[+] Rock bottom;\n" + Style.RESET_ALL)
elif error_method:
banner()
checkasciiwolf()
scan_start()
findAdmin()
print(Fore.RED + Style.BRIGHT + "\n[+] Rock bottom;\n" + Style.RESET_ALL)
else: #in case wordlist cant be found
banner()
opts()
print(Fore.RED + Style.BRIGHT + "[-] Invalid path to the wordlist. File could not be found.\n" + Style.RESET_ALL)
# THIS IS THE STATUS CODE METHOD
示例11
def print_highlighted(line, hl_color=Back.WHITE):
"""
Print a highlighted line
"""
try:
# Highlight positives
colorer = re.compile(r'([^\s]+) POSITIVES: ([1-9]) ')
line = colorer.sub(Fore.YELLOW + r'\1 ' + 'POSITIVES: ' + Fore.YELLOW + r'\2 ' + Style.RESET_ALL, line)
colorer = re.compile(r'([^\s]+) POSITIVES: ([0-9]+) ')
line = colorer.sub(Fore.RED + r'\1 ' + 'POSITIVES: ' + Fore.RED + r'\2 ' + Style.RESET_ALL, line)
# Keyword highlight
colorer = re.compile(r'([A-Z_]{2,}:)\s', re.VERBOSE)
line = colorer.sub(Fore.BLACK + hl_color + r'\1' + Style.RESET_ALL + ' ', line)
print(line)
except Exception as e:
pass
示例12
def printHighlighted(line, hl_color=Back.WHITE, tag_color=False):
"""
Print a highlighted line
"""
if tag_color:
# Tags
colorer = re.compile('(HARMLESS|SIGNED|MS_SOFTWARE_CATALOGUE|MSSOFT|SUCCESSFULLY\sCOMMENTED)', re.VERBOSE)
line = colorer.sub(Fore.BLACK + Back.GREEN + r'\1' + Style.RESET_ALL + '', line)
colorer = re.compile('(REVOKED|EXPLOIT|CVE-[0-9\-]+|OBFUSCATED|RUN\-FILE)', re.VERBOSE)
line = colorer.sub(Fore.BLACK + Back.RED + r'\1' + Style.RESET_ALL + '', line)
colorer = re.compile('(EXPIRED|VIA\-TOR|OLE\-EMBEDDED|RTF|ATTACHMENT|ASPACK|UPX|AUTO\-OPEN|MACROS)', re.VERBOSE)
line = colorer.sub(Fore.BLACK + Back.YELLOW + r'\1' + Style.RESET_ALL + '', line)
# Extras
colorer = re.compile('(\[!\])', re.VERBOSE)
line = colorer.sub(Fore.BLACK + Back.LIGHTMAGENTA_EX + r'\1' + Style.RESET_ALL + '', line)
# Add line breaks
colorer = re.compile('(ORIGNAME:)', re.VERBOSE)
line = colorer.sub(r'\n\1', line)
# Standard
colorer = re.compile('([A-Z_]{2,}:)\s', re.VERBOSE)
line = colorer.sub(Fore.BLACK + hl_color + r'\1' + Style.RESET_ALL + ' ', line)
print(line)
示例13
def scanNumber(InputNumber):
print(code_title + "[!] ---- Fetching informations for {} ---- [!]".format(formatNumber(InputNumber)))
localScan(InputNumber)
global number
global localNumber
global internationalNumber
global numberCountryCode
global numberCountry
if not number:
print((code_error + "Error: number {} is not valid. Skipping.".format(formatNumber(InputNumber))))
sys.exit()
numverifyScan()
ovhScan()
osintScan()
print(code_info + "Scan finished.")
print('\n' + Style.RESET_ALL)
示例14
def test_description(self):
config = sb.objects.config.Config(name="test-project", description="A test project", version="0.1.0")
sbParser = sb.systems.parsing.skeleParser.SkeleParser(config, "test")
description = sbParser.desc
expectedDescription = Style.BRIGHT + "Test Project" + Style.RESET_ALL + """
A test project
-----------------------------------
Version: 0.1.0
Environment: test
Skelebot Version: 6.6.6
-----------------------------------"""
self.assertEqual(description, expectedDescription)
示例15
def test_skelebot_schema_error(self, mock_yaml, exit_mock, print_mock):
mock_yaml.side_effect = SchemaError("Validation Failed")
sb.main()
print_mock.assert_called_once_with(Fore.RED + "ERROR" + Style.RESET_ALL + " | skelebot.yaml | Validation Failed")
exit_mock.assert_called_once_with(1)
示例16
def test_skelebot_runtime_error(self, mock_yaml, exit_mock, print_mock):
mock_yaml.side_effect = RuntimeError("Environment Not Found")
sb.main()
print_mock.assert_called_once_with(Fore.RED + "ERROR" + Style.RESET_ALL + " | Environment Not Found")
exit_mock.assert_called_once_with(1)
示例17
def test_loadConfig_with_bad_plugin(self, mock_getcwd, mock_expanduser, mock_exists, mock_makedirs, mock_shutil, mock_print):
mock_expanduser.return_value = "{path}/test/plugins-bad".format(path=self.path)
mock_getcwd.return_value = "{path}/test/files".format(path=self.path)
mock_exists.side_effect = [True, False]
config = sb.systems.generators.yaml.loadConfig()
folder = "{}/test/plugins-bad/addNumbersBad".format(self.path)
mock_print.assert_called_with(Fore.YELLOW + "WARNING" + Style.RESET_ALL + " | The addNumbersBad plugin contains errors - Adding plugin to Quarantine")
mock_makedirs.assert_called_with("{path}/test/plugins-bad".format(path=self.path))
mock_shutil.assert_called_with(folder, folder)
# Test to ensure that the config loads from skelebot.yaml and overwrites with skelebot-test.yaml properly
示例18
def _get_search(self, cat_i, master, sub):
while True:
try:
search_for = str(input(
Style.BRIGHT + "\nWhat would you like to search for in r/" +
sub + "? " + Style.RESET_ALL)).strip()
if not search_for:
raise ValueError
else:
self._update_master(cat_i, master, search_for, sub)
break
except ValueError:
print("Not an option! Try again.")
### Get number of results.
示例19
def _get_n_results(self, cat_i, master, sub):
while True:
try:
search_for = input(
Style.BRIGHT + "\nHow many results do you want to capture from r/" +
sub + "? " + Style.RESET_ALL).strip()
if search_for.isalpha() or not search_for:
raise ValueError
else:
self._update_master(cat_i, master, search_for, sub)
break
except ValueError:
print("Not an option! Try again.")
### Select post category and the number of results returned from each Subreddit.
示例20
def colorize_direction(direction):
"""
Green for the up direction,
gray for the same, and red for the down direction
"""
if direction == 1:
return Fore.GREEN + '↑' + Style.RESET_ALL
if direction == -1:
return Fore.RED + '↓' + Style.RESET_ALL
return Style.DIM + '=' + Style.RESET_ALL
示例21
def _colorize_frame(s_frame):
"""
Colorize frame in string s_frame
"""
output = []
for line in s_frame.splitlines():
line = line.decode('utf-8')\
.replace(u'lqqqq', Style.DIM + u'lqqqq')\
.replace(u'tqqqq', Style.DIM + u'tqqqq')\
.replace(u'mqqqq', Style.DIM + u'mqqqq')\
.replace(u'x', Style.DIM + u'x' + Style.RESET_ALL)\
.replace(u'qqqqk', u'qqqqk' + Style.RESET_ALL)\
.replace(u'qqqqu', u'qqqqu' + Style.RESET_ALL)\
.replace(u'qqqqj', u'qqqqj' + Style.RESET_ALL)\
.encode('utf-8')
line = line.decode('utf-8')\
.replace(u'┌────', Style.DIM + u'┌────')\
.replace(u'├────', Style.DIM + u'├────')\
.replace(u'└────', Style.DIM + u'└────')\
.replace(u'│', Style.DIM + u'│' + Style.RESET_ALL)\
.replace(u'────┐', u'────┐' + Style.RESET_ALL)\
.replace(u'────┤', u'────┤' + Style.RESET_ALL)\
.replace(u'────┘', u'────┘' + Style.RESET_ALL)\
.encode('utf-8')
output.append(line)
return "\n".join(output)
#
# that's everything we need to save (and to load later)
#
示例22
def _make_messages(self):
output = ""
for line in self.warnings:
output += Fore.YELLOW + "WARNING: %s\n" % line + Style.RESET_ALL
if self.options.get('msg_interval'):
output += MSG_INTERVAL
else:
output += MSG_SEE_HELP
return output + "\n"
示例23
def colorize(self, msg):
"""
Mewarnai pesan
"""
color = self.color_map[self.record.levelno]
reset = Style.RESET_ALL
levelname = reset + color + self.record.levelname + reset
if self.record.levelname == "CRITICAL":
color = self.color_map[logging.ERROR]
name = Fore.LIGHTBLUE_EX + self.record.name + reset
message = self.record.message
# XXX: kenapa cara dibawah ini tidak bekerja?
#
# match = re.findall(r"['\"]+(.*?)['\"]+", message)
# if match:
# match.reverse()
# for m in match:
# message = message.replace(m, color + m + reset, 1)
match = re.search(r"=> (?P<account>.*?(?:| \: .*?)) \((?P<status>[A-Z]+)\)", message)
if match:
account = match.group("account")
status = match.group("status")
if status == "NO":
color_status = Fore.LIGHTRED_EX
else:
color_status = Fore.LIGHTGREEN_EX
newmsg = message.replace(account, color_status + account + reset)
newmsg = newmsg.replace(status, color_status + status + reset)
msg = msg.replace(message, newmsg)
asctime = re.findall(r"\[(.+?)\]", msg)[0]
msg = msg.replace(asctime, Fore.LIGHTMAGENTA_EX + asctime + reset, 1)
msg = msg.replace(self.record.name, name, 1)
msg = msg.replace(self.record.levelname, levelname, 1)
msg = msg + reset
return msg
示例24
def error(text):
text = str(text)
return Back.RED + text + Style.RESET_ALL if Color.is_atty() else text
示例25
def control(text):
text = '\n<<< ' + str(text) + ' >>>\n\r'
return Fore.YELLOW + text + Style.RESET_ALL if Color.is_atty() else text
示例26
def control_without_arrows(text):
text = str(text)
return Fore.YELLOW + text + Style.RESET_ALL if Color.is_atty() else text
示例27
def warning(text):
text = '\n\n<<< Warning: ' + str(text) + ' >>>\n'
return Back.YELLOW + text + Style.RESET_ALL if Color.is_atty() else text
示例28
def success(text):
text = str(text)
return Back.GREEN + text + Style.RESET_ALL if Color.is_atty() else text
示例29
def log(self, msg, state='info'):
if not self.active:
content = f"{Style.BRIGHT + self.states[state][1] if self.os == 'Linux' else ''}[{time.strftime('%X')}] {self.states[state][0]} {msg}{self._RESET}{Style.RESET_ALL}"
print(content)
if self.path:
self._write(msg=msg, state=state)
示例30
def yellowtext(s):
"""Yellow text"""
return Fore.YELLOW + Style.BRIGHT + s + Style.RESET_ALL + Fore.RESET