Python pprint.PrettyPrinter() Examples
The following are 30
code examples of pprint.PrettyPrinter().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pprint
, or try the search function
.
Example #1
Source File: _pprint.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def _pprint_key_val_tuple(self, object, stream, indent, allowance, context, level): """Pretty printing for key-value tuples from dict or parameters.""" k, v = object rep = self._repr(k, context, level) if isinstance(object, KeyValTupleParam): rep = rep.strip("'") middle = '=' else: middle = ': ' stream.write(rep) stream.write(middle) self._format(v, stream, indent + len(rep) + len(middle), allowance, context, level) # Note: need to copy _dispatch to prevent instances of the builtin # PrettyPrinter class to call methods of _EstimatorPrettyPrinter (see issue # 12906)
Example #2
Source File: solution.py From bioinformatics_primer with MIT License | 6 votes |
def main(): """Make a jazz noise here""" args = get_args() pubmed_url = ('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/' 'esummary.fcgi?db=pubmed&retmode=json&id={}') for pubmed_id in args.pubmed_id: r = requests.get(pubmed_url.format(pubmed_id)) if r.status_code == 200: data = json.loads(r.text) result = data.get('result') if result: info = result.get(str(pubmed_id)) if info: pprint.PrettyPrinter().pprint(info) print(info['title'], info['lastauthor']) # --------------------------------------------------
Example #3
Source File: inference_similarity.py From kaggle-humpback with BSD 2-Clause "Simplified" License | 6 votes |
def main(): import warnings warnings.filterwarnings("ignore") print('inference similarities of whales') args = parse_args() if args.config_file is None: raise Exception('no configuration file') config = utils.config.load(args.config_file) pprint.PrettyPrinter(indent=2).pprint(config) dir_name = os.path.dirname(args.output_path) os.makedirs(dir_name, exist_ok=True) run(config, tta_flip=args.tta_flip==1, tta_landmark=args.tta_landmark==1, checkpoint_name=args.checkpoint_name, output_path=args.output_path) print('success!')
Example #4
Source File: test_aggregators.py From ripe-atlas-tools with GNU General Public License v3.0 | 6 votes |
def test_range_aggregation(self): """Test 1 tier range aggregation""" keys = [RangeKeyAggregator(ranges=[10, 20, 30, 40, 50], key='rtt')] buckets = aggregate(self.results, keys) expected_output = { 'RTT: 10-20': [self.Result(id=5, probe=self.Probe(id=5, country='SE', asn=337, status='DisConnected'), rtt=17, source='127.0.0.1', prefix='192/8'), self.Result(id=6, probe=self.Probe(id=6, country='SE', asn=335, status='DisConnected'), rtt=15, source='127.0.0.1', prefix='195/8')], 'RTT: 20-30': [self.Result(id=8, probe=self.Probe(id=8, country='DE', asn=338, status='Connected'), rtt=28, source='127.0.0.1', prefix='192/8'), self.Result(id=10, probe=self.Probe(id=10, country='DE', asn=338, status='NeverConnected'), rtt=28, source='127.0.0.1', prefix='194/8')], 'RTT: 30-40': [self.Result(id=2, probe=self.Probe(id=2, country='NL', asn=334, status='Connected'), rtt=34.0, source='127.0.0.1', prefix='192/8'), self.Result(id=3, probe=self.Probe(id=3, country='SE', asn=335, status='Connected'), rtt=35.0, source='127.0.0.1', prefix='193/8'), self.Result(id=7, probe=self.Probe(id=7, country='IN', asn=335, status='Connected'), rtt=35, source='127.0.0.1', prefix='192/8'), self.Result(id=11, probe=self.Probe(id=11, country='DE', asn=340, status='DisConnected'), rtt=40, source='127.0.0.1', prefix='193/8')], 'RTT: 40-50': [self.Result(id=9, probe=self.Probe(id=9, country='DK', asn=348, status='Connected'), rtt=48, source='127.0.0.1', prefix='195/8')], 'RTT: < 10': [self.Result(id=1, probe=self.Probe(id=1, country='GR', asn=333, status='Connected'), rtt=3, source='127.0.0.1', prefix='192/8'), self.Result(id=4, probe=self.Probe(id=4, country='SE', asn=336, status='DisConnected'), rtt=6, source='127.0.0.1', prefix='193/8')] } self.maxDiff = None import pprint pp = pprint.PrettyPrinter() pp.pprint(buckets) self.assertEquals(buckets, expected_output)
Example #5
Source File: table.py From coursys with GNU General Public License v3.0 | 6 votes |
def pretty_print_objects(self): """ Print a flat list of objects in the table. >>> t = Table() >>> t.append_column("FirstName") >>> t.append_column("LastName") >>> t.append_row( ["Curtis", "Lassam"] ) >>> t.append_row( ["Jonathan", "Lassam"] ) >>> t.pretty_print_objects() { 'FirstName': 'Curtis', 'LastName': 'Lassam'} ------------------- { 'FirstName': 'Jonathan', 'LastName': 'Lassam'} ------------------- """ pretty_print = pprint.PrettyPrinter(indent=4,width=10) list_of_strings = [] for row_map in self.row_maps(): pretty_print.pprint(row_map) print("-------------------")
Example #6
Source File: table.py From coursys with GNU General Public License v3.0 | 6 votes |
def pretty_print_objects(self): """ Print a flat list of objects in the table. >>> t = Table() >>> t.append_column("FirstName") >>> t.append_column("LastName") >>> t.append_row( ["Curtis", "Lassam"] ) >>> t.append_row( ["Jonathan", "Lassam"] ) >>> t.pretty_print_objects() { 'FirstName': 'Curtis', 'LastName': 'Lassam'} ------------------- { 'FirstName': 'Jonathan', 'LastName': 'Lassam'} ------------------- """ pretty_print = pprint.PrettyPrinter(indent=4,width=10) list_of_strings = [] for row_map in self.row_maps(): pretty_print.pprint(row_map) print("-------------------")
Example #7
Source File: bind.py From prpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def print_referrers(obj, dbg=False): import gc for referrer in gc.get_referrers(obj): if isinstance(referrer, dict): for field, value in referrer.items(): if value is obj: print referrer, field elif hasattr(referrer, '__dict__'): for field,value in referrer.__dict__.items(): if value is obj: print referrer, field elif hasattr(referrer, 'remove'): print referrer elif type(referrer) == tuple: clear_referrers(referrer, dbg=True) else: #import pprint #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(referrer) pass
Example #8
Source File: paymentReport.py From grin-pool with Apache License 2.0 | 6 votes |
def main(): CONFIG = lib.get_config() LOGGER = lib.get_logger(PROCESS) LOGGER.warn("=== Starting {}".format(PROCESS)) # Connect to DB database = lib.get_db() database.db.initializeSession() pp = pprint.PrettyPrinter(indent=4) # Fetch and print pool block reward estimates for latest N pool blocks try: pool_blocks = Pool_blocks.get_latest(NUM_BLOCKS) pool_blocks_h = [blk.height for blk in pool_blocks] LOGGER.warn("Will report estimates for pool blocks: {}".format(pool_blocks_h)) # Print Estimate for height in pool_blocks_h: pp.pprint("Eestimate for block: {}".format(height)) payout_map = pool.get_block_payout_map_estimate(height, LOGGER) pp.pprint(payout_map) except Exception as e: # AssertionError as e: LOGGER.error("Something went wrong: {} - {}".format(e, traceback.print_stack())) LOGGER.warn("=== Completed {}".format(PROCESS))
Example #9
Source File: config_generator.py From rift-python with Apache License 2.0 | 6 votes |
def parse_meta_configuration(file_name): try: with open(file_name, 'r') as stream: try: config = yaml.safe_load(stream) except yaml.YAMLError as exception: raise exception except IOError: fatal_error('Could not open input meta-configuration file "{}"'.format(file_name)) validator = cerberus.Validator(SCHEMA) if not validator.validate(config, SCHEMA): pretty_printer = pprint.PrettyPrinter() pretty_printer.pprint(validator.errors) exit(1) return validator.normalized(config)
Example #10
Source File: models.py From CAPTCHA-breaking with MIT License | 6 votes |
def get_config(self, verbose=0): config = super(Model, self).get_config() for p in ['class_mode', 'theano_mode']: if hasattr(self, p): config[p] = getattr(self, p) if hasattr(self, 'optimizer'): config['optimizer'] = self.optimizer.get_config() if hasattr(self, 'loss'): if type(self.loss) == dict: config['loss'] = dict([(k, get_function_name(v)) for k, v in self.loss.items()]) else: config['loss'] = get_function_name(self.loss) if verbose: pp = pprint.PrettyPrinter(indent=4) pp.pprint(config) return config
Example #11
Source File: Environment.py From arnold-usd with Apache License 2.0 | 6 votes |
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)
Example #12
Source File: test_pprint.py From ironpython2 with Apache License 2.0 | 6 votes |
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,))
Example #13
Source File: Environment.py From web2board with GNU Lesser General Public License v3.0 | 6 votes |
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)
Example #14
Source File: gen_opset.py From onnx-tensorflow with Apache License 2.0 | 6 votes |
def main(): backend_opset_dict = {} for schema in defs.get_all_schemas(): op_name = schema.name backend_opset_dict[op_name] = [] backend_onnx_coverage, backend_experimental_op = get_backend_coverage() backend_opset_dict.update(backend_onnx_coverage.get(defs.ONNX_DOMAIN, {})) backend_ps_dict = get_backend_partial_support_detail() with open('opset_version.py', 'w') as version_file: pp = pprint.PrettyPrinter(indent=4) version_file.write("backend_opset_version = {\n " + pp.pformat(backend_opset_dict)[1:-1] + "\n}\n\n") version_file.write("backend_partial_support = {\n " + pp.pformat(backend_ps_dict)[1:-1] + "\n}\n")
Example #15
Source File: _pprint.py From scikit-multiflow with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _pprint_key_val_tuple(self, object, stream, indent, allowance, context, level): """Pretty printing for key-value tuples from dict or parameters.""" k, v = object rep = self._repr(k, context, level) if isinstance(object, KeyValTupleParam): rep = rep.strip("'") middle = '=' else: middle = ': ' stream.write(rep) stream.write(middle) self._format(v, stream, indent + len(rep) + len(middle), allowance, context, level) # Note: need to copy _dispatch to prevent instances of the builtin # PrettyPrinter class to call methods of _EstimatorPrettyPrinter (see issue # 12906)
Example #16
Source File: policies.py From python-viptela with GNU General Public License v3.0 | 6 votes |
def security(ctx, name, json): #pylint: disable=unused-argument """ Show security policy information """ security_policy = SecurityPolicy(ctx.auth, ctx.host) policy_data = PolicyData(ctx.auth, ctx.host) pp = pprint.PrettyPrinter(indent=2) if name: security_policy_dict = security_policy.get_security_policy_dict() if name in security_policy_dict: if json: pp.pprint(security_policy_dict[name]) else: preview = security_policy.get_security_policy_preview(security_policy_dict[name]['policyId']) pp.pprint(preview) else: security_policy_list = policy_data.export_security_policy_list() pp.pprint(security_policy_list)
Example #17
Source File: convert_service.py From f5-openstack-agent with Apache License 2.0 | 6 votes |
def main(args): if len(args) != 2: sys.exit(1) pp = pprint.PrettyPrinter(indent="2") f = codecs.open(args[1], encoding='utf-8') s = f.readline() s = normalize_input(s) try: d = yaml.load(s) except Exception as err: print "Failed to load as yaml: " print err.message print json.dumps(d, indent=4)
Example #18
Source File: policies.py From python-viptela with GNU General Public License v3.0 | 6 votes |
def central(ctx, name, json): #pylint: disable=unused-argument """ Show central policy information """ central_policy = CentralPolicy(ctx.auth, ctx.host) policy_data = PolicyData(ctx.auth, ctx.host) pp = pprint.PrettyPrinter(indent=2) if name: central_policy_dict = central_policy.get_central_policy_dict() if name in central_policy_dict: if json: pp.pprint(central_policy_dict[name]) else: preview = central_policy.get_central_policy_preview(central_policy_dict[name]['policyId']) pp.pprint(preview) else: central_policy_list = policy_data.export_central_policy_list() pp.pprint(central_policy_list)
Example #19
Source File: policies.py From python-viptela with GNU General Public License v3.0 | 6 votes |
def definition(ctx, name, json, definition_type): #pylint: disable=unused-argument """ Show policy definition information """ policy_definitions = PolicyDefinitions(ctx.auth, ctx.host) policy_data = PolicyData(ctx.auth, ctx.host) pp = pprint.PrettyPrinter(indent=2) if name: policy_definition_dict = policy_definitions.get_policy_definition_dict(definition_type) if name in policy_definition_dict: policy_definition = policy_data.export_policy_definition_list(policy_definition_dict[name]['type'].lower()) # list_keys(policy_definition['definition']) pp.pprint(policy_definition) else: policy_definition_list = policy_data.export_policy_definition_list(definition_type) pp.pprint(policy_definition_list)
Example #20
Source File: templates.py From python-viptela with GNU General Public License v3.0 | 6 votes |
def templates(ctx, input_file, check, update, diff, name, template_type): """ Import templates from file """ vmanage_files = Files(ctx.auth, ctx.host) pp = pprint.PrettyPrinter(indent=2) click.echo(f'Importing templates from {input_file}') result = vmanage_files.import_templates_from_file(input_file, update=update, check_mode=check, name_list=name, template_type=template_type) print(f"Feature Template Updates: {len(result['feature_template_updates'])}") if diff: for diff_item in result['feature_template_updates']: click.echo(f"{diff_item['name']}:") pp.pprint(diff_item['diff']) print(f"Device Template Updates: {len(result['device_template_updates'])}") if diff: for diff_item in result['device_template_updates']: click.echo(f"{diff_item['name']}:") pp.pprint(diff_item['diff'])
Example #21
Source File: console.py From django2-project-template with MIT License | 6 votes |
def oprint(self, input_txt, **options): source = self.options['source'] if 'source' in options.keys(): source = '{0} : {1}'.format(source, options.pop('source')) self.configure(**options) self.pp = pprint.PrettyPrinter(indent=self.options['indent'], width=self.options['width'], compact=True) header = self.options['seperator_line'].format( source='[{0}]'.format(source), char=self.options['seperator_char'], width=self.options['width'] ) footer = self.options['seperator_char'] * self.options['width'] sys.stdout.write(self.colorize(header)) sys.stdout.write('\n') self.pp.pprint(input_txt) sys.stdout.write(self.colorize(footer)) sys.stdout.write('\n' * 2)
Example #22
Source File: Environment.py From pivy with ISC License | 6 votes |
def Dump(self, key = None): """ Using the standard Python pretty printer, dump the contents of the scons build environment to stdout. 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)
Example #23
Source File: route.py From python-viptela with GNU General Public License v3.0 | 5 votes |
def table(ctx, device, json): """ Show Interfaces """ vmanage_device = Device(ctx.auth, ctx.host) # Check to see if we were passed in a device IP address or a device name try: ip = ipaddress.ip_address(device) system_ip = ip except ValueError: device_dict = vmanage_device.get_device_status(device, key='host-name') if 'system-ip' in device_dict: system_ip = device_dict['system-ip'] else: system_ip = None if not json: click.echo("VPNID PREFIX NEXT HOP PROTOCOL ") click.echo("----------------------------------------------------------------") routes = vmanage_device.get_device_data('ip/routetable', system_ip) for rte in routes: if json: pp = pprint.PrettyPrinter(indent=2) pp.pprint(rte) else: if 'nexthop-addr' not in rte: rte['nexthop-addr'] = '' click.echo(f"{rte['vpn-id']:5} {rte['prefix']:<20} {rte['nexthop-addr']:<20} {rte['protocol']:8}")
Example #24
Source File: generate_report.py From royal-chaos with MIT License | 5 votes |
def write2json(path, result): with open(path, 'w', newline='') as file: # pp = pprint.PrettyPrinter(stream=file) # pp.pprint(json.dumps(result)) file.write(json.dumps(result))
Example #25
Source File: make-setup.py From cqparts with Apache License 2.0 | 5 votes |
def setup_standin(**kwargs): # Used instead of `setuptools.setup`; # Write a clean `setup.py` file to execute or building & installation. # # "Why on earth are you doing this?" I hear you ask: # "That's a fair question" I reply... # # originally this *was* the `setup.py` file used to *build* the distribution files. # However, I have since learnt is that the `setup.py` file itself is # distributed with the build module(s). It is used to *install* the library on # each end-user's system. # # I think you'll agree that the above code has no place on an end-user's # system; it's highly reliant on it being executed from inside this repository. # # Therefore, I've chosen to serialize the kwargs designed for `setuptools.setup` # and write them to a very simple `setup.py` file. # Normally I abhor unnecessarily generating code to execute, but I believe, # in this case, it's necessary to keep deployment clean. params_str = pprint.PrettyPrinter(indent=2).pformat(kwargs) with open('setup.py.jinja', 'r') as tmp, open(os.path.join(LIB_PARENT_DIR, 'setup.py'), 'w') as output: template = jinja2.Template(tmp.read()) output.write(template.render(params=params_str)) #setuptools.setup(
Example #26
Source File: test_pprint.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
def test_builtin_prettyprinter(): # non regression test than ensures we can still use the builtin # PrettyPrinter class for estimators (as done e.g. by joblib). # Used to be a bug PrettyPrinter().pprint(LogisticRegression())
Example #27
Source File: test_pprint.py From oss-ftp with MIT License | 5 votes |
def test_unreadable(self): # Not recursive but not readable anyway pp = pprint.PrettyPrinter() for unreadable in type(3), pprint, pprint.isrecursive: # module-level convenience functions self.assertFalse(pprint.isrecursive(unreadable), "expected not isrecursive for %r" % (unreadable,)) self.assertFalse(pprint.isreadable(unreadable), "expected not isreadable for %r" % (unreadable,)) # PrettyPrinter methods self.assertFalse(pp.isrecursive(unreadable), "expected not isrecursive for %r" % (unreadable,)) self.assertFalse(pp.isreadable(unreadable), "expected not isreadable for %r" % (unreadable,))
Example #28
Source File: controller.py From neural-architecture-search with MIT License | 5 votes |
def print_state_space(self): ''' Pretty print the state space ''' print('*' * 40, 'STATE SPACE', '*' * 40) pp = pprint.PrettyPrinter(indent=2, width=100) for id, state in self.states.items(): pp.pprint(state) print()
Example #29
Source File: policies.py From python-viptela with GNU General Public License v3.0 | 5 votes |
def list_cmd(ctx, name, json, policy_list_type): #pylint: disable=unused-argument """ Show policy list information """ policy_lists = PolicyLists(ctx.auth, ctx.host) pp = pprint.PrettyPrinter(indent=2) if name: policy_list_dict = policy_lists.get_policy_list_dict(policy_list_type=policy_list_type) if name in policy_list_dict: pp.pprint(policy_list_dict[name]) else: policy_lists = policy_lists.get_policy_list_list(policy_list_type=policy_list_type) pp.pprint(policy_lists)
Example #30
Source File: policies.py From python-viptela with GNU General Public License v3.0 | 5 votes |
def policies(ctx, input_file, check, update, push, diff): """ Import policies from file """ vmanage_files = Files(ctx.auth, ctx.host) pp = pprint.PrettyPrinter(indent=2) click.echo(f"{'Checking' if check else 'Importing'} policies from {input_file}") result = vmanage_files.import_policy_from_file(input_file, update=update, check_mode=check, push=push) print(f"Policy List Updates: {len(result['policy_list_updates'])}") if diff: for diff_item in result['policy_list_updates']: click.echo(f"{diff_item['name']}:") pp.pprint(diff_item['diff']) print(f"Policy Definition Updates: {len(result['policy_definition_updates'])}") if diff: for diff_item in result['policy_definition_updates']: click.echo(f"{diff_item['name']}:") pp.pprint(diff_item['diff']) print(f"Central Policy Updates: {len(result['central_policy_updates'])}") if diff: for diff_item in result['central_policy_updates']: click.echo(f"{diff_item['name']}:") pp.pprint(diff_item['diff']) print(f"Local Policy Updates: {len(result['local_policy_updates'])}") if diff: for diff_item in result['local_policy_updates']: click.echo(f"{diff_item['name']}:") pp.pprint(diff_item['diff']) print(f"Security Policy Updates: {len(result['security_policy_updates'])}") if diff: for diff_item in result['security_policy_updates']: click.echo(f"{diff_item['name']}:") pp.pprint(diff_item['diff'])