当前位置: 首页>>代码示例>>Python>>正文


Python pprint.PrettyPrinter方法代码示例

本文整理汇总了Python中pprint.PrettyPrinter方法的典型用法代码示例。如果您正苦于以下问题:Python pprint.PrettyPrinter方法的具体用法?Python pprint.PrettyPrinter怎么用?Python pprint.PrettyPrinter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块pprint的用法示例。

在下文中一共展示了pprint.PrettyPrinter方法的26个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_range_aggregation

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:RIPE-NCC,项目名称:ripe-atlas-tools,代码行数:18,代码来源:test_aggregators.py


示例2: pretty_print_objects

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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("-------------------") 
开发者ID:sfu-fas,项目名称:coursys,代码行数:24,代码来源:table.py


示例3: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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!') 
开发者ID:pudae,项目名称:kaggle-humpback,代码行数:21,代码来源:inference_similarity.py


示例4: get_config

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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 
开发者ID:lllcho,项目名称:CAPTCHA-breaking,代码行数:19,代码来源:models.py


示例5: Dump

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:Autodesk,项目名称:arnold-usd,代码行数:19,代码来源:Environment.py


示例6: test_basic

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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,)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:test_pprint.py


示例7: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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") 
开发者ID:onnx,项目名称:onnx-tensorflow,代码行数:19,代码来源:gen_opset.py


示例8: _pprint_key_val_tuple

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:scikit-multiflow,项目名称:scikit-multiflow,代码行数:20,代码来源:_pprint.py


示例9: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:F5Networks,项目名称:f5-openstack-agent,代码行数:20,代码来源:convert_service.py


示例10: Dump

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:coin3d,项目名称:pivy,代码行数:19,代码来源:Environment.py


示例11: oprint

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:vigo,项目名称:django2-project-template,代码行数:22,代码来源:console.py


示例12: templates

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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']) 
开发者ID:CiscoDevNet,项目名称:python-viptela,代码行数:25,代码来源:templates.py


示例13: definition

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:CiscoDevNet,项目名称:python-viptela,代码行数:19,代码来源:policies.py


示例14: central

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:CiscoDevNet,项目名称:python-viptela,代码行数:21,代码来源:policies.py


示例15: security

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:CiscoDevNet,项目名称:python-viptela,代码行数:21,代码来源:policies.py


示例16: print_referrers

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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 
开发者ID:personalrobotics,项目名称:prpy,代码行数:22,代码来源:bind.py


示例17: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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)) 
开发者ID:grin-pool,项目名称:grin-pool,代码行数:27,代码来源:paymentReport.py


示例18: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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'])


# -------------------------------------------------- 
开发者ID:kyclark,项目名称:bioinformatics_primer,代码行数:22,代码来源:solution.py


示例19: log_environment

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
def log_environment():
    instance_id = ec2_instance_id_hostname()
    if instance_id:
        logging.info("EC2 Instance id: %s", instance_id)
    pp = pprint.PrettyPrinter(indent=4)
    logging.debug("Build environment: %s", pp.pformat(dict(os.environ))) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:8,代码来源:build.py


示例20: parse_meta_configuration

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
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) 
开发者ID:brunorijsman,项目名称:rift-python,代码行数:17,代码来源:config_generator.py


示例21: parse_configuration

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
def parse_configuration(filename):
    if filename:
        try:
            file = open(filename, 'r')
        except (OSError, IOError) as err:
            print("Could not open configuration file {} ({})".format(filename, err),
                  file=sys.stderr)
            sys.exit(1)
        try:
            config = yaml.safe_load(file)
        except yaml.YAMLError as err:
            print("Could not load configuration file {}: {}".format(filename, str(err)),
                  file=sys.stderr)
            file.close()
            sys.exit(1)
        file.close()
    else:
        config = DEFAULT_CONFIG
    validator = RiftValidator(SCHEMA)
    if not validator.validate(config, SCHEMA):
        print("Could not parse configuration file {}:".format(filename), file=sys.stderr)
        pretty_printer = pprint.PrettyPrinter()
        pretty_printer.pprint(validator.errors)
        exit(1)
    config = validator.normalized(config)
    apply_global_defaults(config)
    apply_inheritance(config)
    apply_inferences(config)
    return config 
开发者ID:brunorijsman,项目名称:rift-python,代码行数:31,代码来源:config.py


示例22: __str__

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
def __str__(self):
        import pprint
        P = pprint.PrettyPrinter()
        return P.pformat(self.as_nameddict()) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:6,代码来源:protocol.py


示例23: printpickle

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
def printpickle():
	pp = pprint.PrettyPrinter(indent=4)

	with open(sys.argv[1], 'rb') as f:
		p = pickle.load(f)
		pp.pprint(p) 
开发者ID:dobin,项目名称:ffw,代码行数:8,代码来源:printpickle.py


示例24: print_attributes

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
def print_attributes(oLine):
    pp = pprint.PrettyPrinter(indent = 4)
    pp.pprint(oLine.__dict__) 
开发者ID:jeremiah-c-leary,项目名称:vhdl-style-guide,代码行数:5,代码来源:utils.py


示例25: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
def main():
    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)
    run(config, args.num_checkpoint, args.epoch_end, args.output_filename)

    print('success!') 
开发者ID:pudae,项目名称:kaggle-humpback,代码行数:12,代码来源:swa.py


示例26: main

# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import PrettyPrinter [as 别名]
def main():
    import warnings
    warnings.filterwarnings("ignore")

    print('Train humpback whale identification')
    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)
    utils.prepare_train_directories(config)
    run(config)
    print('success!') 
开发者ID:pudae,项目名称:kaggle-humpback,代码行数:16,代码来源:train.py



注:本文中的pprint.PrettyPrinter方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。