def display_ec2_tags(self, outputformat='json',
filter=None, aggr_and=False):
'''
Display Tags for all EC2 Resources
'''
ec2_client = aws_service.AwsService('ec2')
tagsobj = ec2_client.service.list_tags()
if filter is not None:
tagsobj = orcautils.filter_dict(tagsobj,
filter,
aggr_and=aggr_and)
if outputformat == "json":
pprinter = pprint.PrettyPrinter()
pprinter.pprint(tagsobj)
else:
self.display_ec2_tags_table(tagsobj)
python类PrettyPrinter()的实例源码
def display_s3_bucketlist(self, outputformat='json',
filter=None, output_fields=None,
aggr_and=False):
'''
Display the List of S3 buckets
'''
service_client = aws_service.AwsService('s3')
bucketlist = service_client.service.list_buckets_fast()
newbucketlist = service_client.service.populate_bucket_fast("location",
bucketlist)
newbucketlist = service_client.service.populate_bucket_fast(
"objects",
newbucketlist)
if filter is not None:
newbucketlist = orcautils.filter_list(newbucketlist,
filter,
aggr_and=aggr_and)
if outputformat == "json":
pprinter = pprint.PrettyPrinter()
pprinter.pprint(newbucketlist)
else:
self.display_s3_buckelist_table(newbucketlist)
def display_s3_bucket_validations(self, outputformat='json'):
'''
Display the list of S3 buckets and the validation results.
'''
s3client = aws_service.AwsService('s3')
bucketlist = s3client.service.list_buckets()
#s3client.service.populate_bucket_tagging(bucketlist)
#s3client.service.populate_bucket_validation(bucketlist)
newbucketlist = s3client.service.populate_bucket_fast("tagging",
bucketlist)
newbucketlist = s3client.service.populate_bucket_fast("validation",
newbucketlist)
if outputformat == "json":
pprinter = pprint.PrettyPrinter()
pprinter.pprint(newbucketlist)
else:
self.display_s3_bucket_validations_table(newbucketlist)
def pprint(to_be_printed):
"""nicely formated print"""
try:
import pprint as pp
# generate an instance PrettyPrinter
# pp.PrettyPrinter().pprint(to_be_printed)
pp.pprint(to_be_printed)
except ImportError:
if isinstance(to_be_printed, dict):
print('{')
for k, v in to_be_printed.items():
print("'" + k + "'" if str(k) == k else k,
': ',
"'" + v + "'" if str(v) == v else v,
sep="")
print('}')
else:
print('could not import pprint module, appling regular print')
print(to_be_printed)
# todo: this should rather be a class instance
def print_progress_bar(progress_array, iteration, prefix='', suffix='', bar_length=100):
"""
Prints a progress bar
"""
str_format = "{0:.1f}"
total = len(progress_array)
percents = str_format.format(100 * (iteration / float(total)))
fill_length = int(round(bar_length / float(total)))
bar_symbol = ''
for idx, pos in enumerate(progress_array):
if idx == iteration:
bar_symbol += (PrettyPrinter.yellow(u'?') * fill_length)
elif pos is None:
bar_symbol += ('-' * fill_length)
elif pos:
bar_symbol += (PrettyPrinter.green(u'?') * fill_length)
else:
bar_symbol += (PrettyPrinter.red(u'?') * fill_length)
# pylint: disable=W0106
sys.stdout.write(u'\x1b[2K\r{} |{}| {}{} {}\n'
.format(prefix, bar_symbol, percents, '%', suffix)),
sys.stdout.flush()
def list_apps(ctx):
environment = ctx.parent.params['environment']
config_parser = configparser.ConfigParser()
config_parser.read(CONFIG_PATH)
if sys.version_info[0] < 3 and environment.lower() == 'default':
environment = configparser.DEFAULTSECT
client_id = config_parser.get(environment, 'client_id')
client_secret = config_parser.get(environment, 'client_secret')
response = management_utils.list_apps((client_id, client_secret))
if response.ok:
app_data = response.json()
else:
click.echo(response.text)
printer = pprint.PrettyPrinter(indent=4)
printer.pprint(app_data)
def __init__(self, app):
# Initiate the parent class
cmd.Cmd.__init__(self)
# Set up the command line prompt itself
self.prompt = "Tuxemon>> "
self.intro = 'Tuxemon CLI\nType "help", "copyright", "credits" or "license" for more information.'
# Import pretty print so that shit is formatted nicely
import pprint
self.pp = pprint.PrettyPrinter(indent=4)
# Import threading to start the CLI in a separate thread
from threading import Thread
self.app = app
self.cmd_thread = Thread(target=self.cmdloop)
self.cmd_thread.daemon = True
self.cmd_thread.start()
def export_as_python(request):
"""Export site settings as a dictionary of dictionaries"""
from livesettings.models import Setting, LongSetting
import pprint
work = {}
both = list(Setting.objects.all())
both.extend(list(LongSetting.objects.all()))
for s in both:
sitesettings = work.setdefault(s.site.id, {'DB': False, 'SETTINGS': {}})['SETTINGS']
sitegroup = sitesettings.setdefault(s.group, {})
sitegroup[s.key] = s.value
pp = pprint.PrettyPrinter(indent=4)
pretty = pp.pformat(work)
return render(request, 'livesettings/text.txt', {'text': pretty}, content_type='text/plain')
# Required permission `is_superuser` is equivalent to auth.change_user,
# because who can modify users, can easy became a superuser.
def load_structure(raw_data):
pp = pprint.PrettyPrinter(indent=4)
#pp.pprint(raw_data[0]); exit(0)
#
print('Stracting from Spotify')
for raw_song_data in raw_data:
song_details = {}
song_details['title'] = raw_song_data['track']['name']
artists = ''
for saltimbanqui in raw_song_data['track']['artists']:
artists = artists + saltimbanqui['name'] + " "
song_details['artist'] = artists
try:
album_pic = raw_song_data['track']['album']['images'][0]['url']
song_details['album_pic'] = album_pic
except:
break
songs_to_dl.append(song_details)
def pprint(to_be_printed):
"""nicely formated print"""
try:
import pprint as pp
# generate an instance PrettyPrinter
# pp.PrettyPrinter().pprint(to_be_printed)
pp.pprint(to_be_printed)
except ImportError:
if isinstance(to_be_printed, dict):
print('{')
for k, v in list(to_be_printed.items()):
print("'" + k + "'" if isinstance(k, str) else k,
': ',
"'" + v + "'" if isinstance(k, str) else v,
sep="")
print('}')
else:
print('could not import pprint module, appling regular print')
print(to_be_printed)
def main():
"""
A sample usage of ids_parser()
"""
import pprint
printer = pprint.PrettyPrinter(indent=4)
parser = ids_parser()
rules = []
with open(sys.argv[1], 'r') as rules_fh:
for line in rules_fh.readlines():
try:
result = parser.parse(line)
except SyntaxError as error:
print "invalid rule, %s : original rule: %s" % (error,
repr(line))
if len(result):
rules.append(result)
printer.pprint(rules)
def pprint(to_be_printed):
"""nicely formated print"""
try:
import pprint as pp
# generate an instance PrettyPrinter
# pp.PrettyPrinter().pprint(to_be_printed)
pp.pprint(to_be_printed)
except ImportError:
if isinstance(to_be_printed, dict):
print('{')
for k, v in list(to_be_printed.items()):
print("'" + k + "'" if isinstance(k, str) else k,
': ',
"'" + v + "'" if isinstance(k, str) else v,
sep="")
print('}')
else:
print('could not import pprint module, appling regular print')
print(to_be_printed)
def tagindexdump(bot, _event, *_args):
"""dump raw contents of tags indices"""
printer = pprint.PrettyPrinter(indent=2)
printer.pprint(bot.tags.indices)
chunks = []
for relationship in bot.tags.indices:
lines = [_("index: <b><i>{}</i></b>").format(relationship)]
for key, items in bot.tags.indices[relationship].items():
lines.append(_("key: <i>{}</i>").format(key))
for item in items:
lines.append("... <i>{}</i>".format(item))
if not lines:
continue
chunks.append("\n".join(lines))
if not chunks:
chunks = [_("<b>no entries to list</b>")]
return "\n\n".join(chunks)
def extract_details_from_nrt (nrt_struct):
"""
Extract some details of call events
"""
# DEBUG
# print (nrt_struct.prettyPrint())
# Translate the NRT structure into a Python one
py_nrt = py_encode (nrt_struct)
# DEBUG
# pp = pprint.PrettyPrinter (indent = 2)
# pp.pprint (py_nrt)
#
return py_nrt
def pprint(to_be_printed):
"""nicely formated print"""
try:
import pprint as pp
# generate an instance PrettyPrinter
# pp.PrettyPrinter().pprint(to_be_printed)
pp.pprint(to_be_printed)
except ImportError:
if isinstance(to_be_printed, dict):
print('{')
for k, v in to_be_printed.items():
print("'" + k + "'" if isinstance(k, basestring) else k,
': ',
"'" + v + "'" if isinstance(k, basestring) else v,
sep="")
print('}')
else:
print('could not import pprint module, appling regular print')
print(to_be_printed)
def test_basic(self):
# Verify .isrecursive() and .isreadable() w/o recursion
pp = pprint.PrettyPrinter()
for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, uni("yaddayadda"),
bytearray(b"ghi"), True, False, None,
self.a, self.b):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_basic(self):
# Verify .isrecursive() and .isreadable() w/o recursion
pp = pprint.PrettyPrinter()
for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, uni("yaddayadda"),
bytearray(b"ghi"), True, False, None,
self.a, self.b):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def Dump(self, key = None):
"""
Using the standard Python pretty printer, return the contents of the
scons build environment as a string.
If the key passed in is anything other than None, then that will
be used as an index into the build environment dictionary and
whatever is found there will be fed into the pretty printer. Note
that this key is case sensitive.
"""
import pprint
pp = pprint.PrettyPrinter(indent=2)
if key:
dict = self.Dictionary(key)
else:
dict = self.Dictionary()
return pp.pformat(dict)
def import_summerdata(exampleName,actionDirectory):
import parsingSummerActionAndFluentOutput
fluent_parses = parsingSummerActionAndFluentOutput.readFluentResults(exampleName)
action_parses = parsingSummerActionAndFluentOutput.readActionResults("{}.{}".format(actionDirectory,exampleName))
#import pprint
#pp = pprint.PrettyPrinter(depth=6)
#pp.pprint(action_parses)
#pp.pprint(fluent_parses)
return [fluent_parses, action_parses]
def display_ec2_vmlist(self, outputformat='json'):
'''
Display the List of EC2 buckets
'''
service_client = aws_service.AwsService('ec2')
vmlist = service_client.service.list_vms()
if outputformat == "json":
pprinter = pprint.PrettyPrinter()
pprinter.pprint(vmlist)
else:
self.display_ec2_vmlist_table(vmlist)
def display_ec2_nw_interfaces(self, outputformat="json"):
'''
Display network interfaces
'''
ec2_client = aws_service.AwsService('ec2')
nw_interfaces = ec2_client.service.list_network_interfaces()
if outputformat == "json":
pprinter = pprint.PrettyPrinter()
pprinter.pprint(nw_interfaces)
else:
self.display_ec2_nw_interfaces_table(nw_interfaces)
def display_iam_userlist(self, outputformat='json'):
'''
Display the list of users.
'''
service_client = aws_service.AwsService('iam')
userlist = service_client.service.list_users()
service_client.service.populate_groups_in_users(userlist)
if outputformat == "json":
pprinter = pprint.PrettyPrinter()
pprinter.pprint(userlist)
else:
self.display_iam_userlist_table(userlist)
def display_iam_user_policies(self,
user_name,
outputformat='json'):
'''
Display policies attached to the user.
'''
awsconfig = aws_config.AwsConfig()
profiles = awsconfig.get_profiles()
service_client = aws_service.AwsService('iam')
policyinfo = {}
for profile in profiles:
policyinfo[profile] = []
policies = service_client.service.get_user_attached_policies(
UserName=user_name,
profile_name=profile)
policyinfo[profile] = policies
if outputformat == "json":
pprinter = pprint.PrettyPrinter()
pprinter.pprint(policyinfo)
if outputformat == "table":
self.display_iam_user_policies_table(user_name,
policyinfo)
def perform_profile_operations(self, namespace):
'''
Handle the profile operations
'''
awsconfig = aws_config.AwsConfig()
profiles = awsconfig.get_profiles()
profile_summary = {}
for profile in profiles:
profile_summary[profile] = {}
profile_summary[profile]['access_key_id'] = \
awsconfig.get_aws_access_key_id(profile)
profile_summary[profile]['secret_access_key'] = \
awsconfig.get_aws_secret_access_key(profile)
if namespace.output == "json":
pprinter = pprint.PrettyPrinter()
pprinter.pprint(profile_summary)
else:
# Setup table.
header = ["Profile Name", "Access Key ID", "Secret Access Key"]
table = prettytable.PrettyTable(header)
for profile in profile_summary.keys():
row = [profile,
profile_summary[profile]['access_key_id'],
profile_summary[profile]['secret_access_key']]
table.add_row(row)
print table
def printWatchlistHits(serverurl, watchlistid, watchlisttype, rows):
global cb
pp = pprint.PrettyPrinter(indent=2)
print rows
getparams = {"cb.urlver": 1,
"watchlist_%d" % watchlistid : "*",
"rows": rows }
if watchlisttype == 'modules':
getparams["cb.q.server_added_timestamp"] = "-1440m"
r = cb.cbapi_get("%s/api/v1/binary?%s" % (serverurl, urllib.urlencode(getparams)))
parsedjson = json.loads(r.text)
pp.pprint(parsedjson)
elif watchlisttype == 'events':
getparams["cb.q.start"] = "-1440m"
r = cb.cbapi_get("%s/api/v1/process?%s" % (serverurl, urllib.urlencode(getparams)))
parsedjson = json.loads(r.text)
pp.pprint(parsedjson)
else:
return
print
print "Total Number of results returned: %d" % len(parsedjson['results'])
print
def printWatchlistHits(serverurl, watchlistid, watchlisttype, rows):
global cb
pp = pprint.PrettyPrinter(indent=2)
print rows
getparams = {"cb.urlver": 1,
"watchlist_%d" % watchlistid : "*",
"rows": rows }
if watchlisttype == 'modules':
getparams["cb.q.server_added_timestamp"] = "-1440m"
r = cb.cbapi_get("%s/api/v1/binary?%s" % (serverurl, urllib.urlencode(getparams)))
parsedjson = json.loads(r.text)
pp.pprint(parsedjson)
elif watchlisttype == 'events':
getparams["cb.q.start"] = "-1440m"
r = cb.cbapi_get("%s/api/v1/process?%s" % (serverurl, urllib.urlencode(getparams)))
parsedjson = json.loads(r.text)
pp.pprint(parsedjson)
else:
return
print
print "Total Number of results returned: %d" % len(parsedjson['results'])
print
def check_root_privileges():
"""
This function checks if the current user is root.
If the user is not root it exits immediately.
"""
if os.getuid() != 0:
# check if root user
PrettyPrinter.println(PrettyPrinter.red("Root privileges are required to run this tool"))
sys.exit(1)
def _format(color, text):
"""
Generic pretty print string formatter
"""
return u"{}{}{}".format(color, text, PrettyPrinter.Colors.ENDC)
def header(text):
"""
Formats text as header
"""
return PrettyPrinter._format(PrettyPrinter.Colors.HEADER, text)
def bold(text):
"""
Formats text as bold
"""
return PrettyPrinter._format(PrettyPrinter.Colors.BOLD, text)