pprint
---数据漂亮打印机¶
源代码: Lib/pprint.py
这个 pprint
模块提供了以一种可以用作解释器输入的形式“完美打印”任意python数据结构的能力。如果格式化结构包含的对象不是基本的Python类型,则表示可能无法加载。如果包含文件、套接字或类等对象,以及许多不能表示为Python文本的其他对象,则可能会出现这种情况。
如果可以的话,格式化的表示将对象保留在一行上,如果对象不在允许的宽度内,则将其拆分为多行。构建 PrettyPrinter
对象,如果需要调整宽度约束。
在计算显示之前,字典按键排序。
在 3.9 版更改: 增加了对漂亮打印的支持 types.SimpleNamespace
.
这个 pprint
模块定义一个类:
- class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False, sort_dicts=True)¶
构建一个
PrettyPrinter
实例。此构造函数了解几个关键字参数。输出流可以使用 流动 关键字;流对象上使用的唯一方法是文件协议的write()
方法。如果未指定,则PrettyPrinter
采用sys.stdout
. 为每个递归级别添加的缩进量由指定 缩进 ;默认值为1。其他值可能会使输出看起来有点奇怪,但可以使嵌套更容易被发现。可以打印的层数由 深度 ;如果要打印的数据结构太深,则下一个包含的级别将替换为...
. 默认情况下,对正在格式化的对象的深度没有限制。所需的输出宽度使用 宽度 参数;默认为80个字符。如果不能在限定的宽度内格式化结构,将尽最大努力。如果 契约 如果为false(默认值),则长序列的每个项都将在单独的行上格式化。如果 契约 是真的,在 宽度 将在每个输出行上格式化。如果 sort_dicts 为true(默认值),字典将按其键排序,否则将按插入顺序显示。在 3.4 版更改: 增加了 契约 参数。
在 3.8 版更改: 增加了 sort_dicts 参数。
>>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff[:]) >>> pp = pprint.PrettyPrinter(indent=4) >>> pp.pprint(stuff) [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> pp = pprint.PrettyPrinter(width=41, compact=True) >>> pp.pprint(stuff) [['spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ... ('parrot', ('fresh fruit',)))))))) >>> pp = pprint.PrettyPrinter(depth=6) >>> pp.pprint(tup) ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))
这个 pprint
模块还提供了几个快捷功能:
- pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)¶
返回的格式化表示形式 object 作为字符串。 缩进 , 宽度 , 深度 , 契约 和 sort_dicts 将传递给
PrettyPrinter
作为格式参数的构造函数。在 3.4 版更改: 增加了 契约 参数。
在 3.8 版更改: 增加了 sort_dicts 参数。
- pprint.pp(object, *args, sort_dicts=False, **kwargs)¶
打印的格式化表示形式 object 然后是换行符。如果 sort_dicts 如果为false(默认值),字典将按插入顺序显示其键,否则将对dict键进行排序。 args 和 关键字参数 将传递给
pprint()
作为格式参数。3.8 新版功能.
- pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)¶
打印的格式化表示形式 object 在 流动 ,然后是换行符。如果 流动 是
None
,sys.stdout
使用。这可以在交互式解释器中使用,而不是print()
用于检查值的函数(甚至可以重新分配print = pprint.pprint
用于范围内)。 缩进 , 宽度 , 深度 , 契约 和 sort_dicts 将传递给PrettyPrinter
作为格式参数的构造函数。在 3.4 版更改: 增加了 契约 参数。
在 3.8 版更改: 增加了 sort_dicts 参数。
>>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff) >>> pprint.pprint(stuff) [<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']
- pprint.isreadable(object)¶
确定 对象 是“可读的”,或者可以使用
eval()
.这总会回来的False
对于递归对象。>>> pprint.isreadable(stuff) False
- pprint.isrecursive(object)¶
确定是否 object 需要递归表示。
还定义了一个支持函数:
- pprint.saferepr(object)¶
返回的字符串表示形式 object ,防止递归数据结构。如果代表 object 显示递归项,递归引用将表示为
<Recursion on typename with id=number>
. 表示形式没有其他格式。>>> pprint.saferepr(stuff) "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
预打印器对象¶
PrettyPrinter
实例具有以下方法:
- PrettyPrinter.pformat(object)¶
返回的格式化表示形式 object . 这考虑了传递给
PrettyPrinter
构造函数。
- PrettyPrinter.pprint(object)¶
打印的格式化表示形式 object 在配置的流上,然后是换行符。
以下方法提供了相同名称对应函数的实现。在实例上使用这些方法比在新实例上使用这些方法效率稍高 PrettyPrinter
不需要创建对象。
- PrettyPrinter.isreadable(object)¶
确定对象的格式化表示是“可读的”,还是可以使用
eval()
. 请注意,这将返回False
对于递归对象。如果 深度 的参数PrettyPrinter
如果设置了且对象深度超过允许值,则返回False
.
- PrettyPrinter.isrecursive(object)¶
确定对象是否需要递归表示。
此方法作为一个钩子提供,以允许子类修改对象转换为字符串的方式。默认实现使用 saferepr()
实施。
- PrettyPrinter.format(object, context, maxlevels, level)¶
返回三个值:格式化版本的 object 作为字符串,指示结果是否可读的标志,以及指示是否检测到递归的标志。第一个参数是要呈现的对象。第二个是一本字典,其中包含
id()
属于当前表示上下文的对象(直接和间接容器 object 影响演示的)作为键;如果需要演示已在中表示的对象 context ,第三个返回值应为True
. 递归调用format()
方法应为此字典添加容器的其他条目。第三个参数, 最大电平 ,将请求的限制设置为递归;这将是0
如果没有要求的限制。此参数应未经修改地传递给递归调用。第四个参数, level ,给出当前级别;递归调用的传递值应小于当前调用的值。
例子¶
演示 pprint()
函数及其参数,让我们从 PyPI ::
>>> import json
>>> import pprint
>>> from urllib.request import urlopen
>>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
... project_info = json.load(resp)['info']
以其基本形式, pprint()
显示整个对象:
>>> pprint.pprint(project_info)
{'author': 'The Python Packaging Authority',
'author_email': 'pypa-dev@googlegroups.com',
'bugtrack_url': None,
'classifiers': ['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Build Tools'],
'description': 'A sample Python project\n'
'=======================\n'
'\n'
'This is the description file for the project.\n'
'\n'
'The file should use UTF-8 encoding and be written using '
'ReStructured Text. It\n'
'will be used to generate the project webpage on PyPI, and '
'should be written for\n'
'that purpose.\n'
'\n'
'Typical contents for this file would include an overview of '
'the project, basic\n'
'usage examples, etc. Generally, including the project '
'changelog in here is not\n'
'a good idea, although a simple "What\'s New" section for the '
'most recent version\n'
'may be appropriate.',
'description_content_type': None,
'docs_url': None,
'download_url': 'UNKNOWN',
'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
'home_page': 'https://github.com/pypa/sampleproject',
'keywords': 'sample setuptools development',
'license': 'MIT',
'maintainer': None,
'maintainer_email': None,
'name': 'sampleproject',
'package_url': 'https://pypi.org/project/sampleproject/',
'platform': 'UNKNOWN',
'project_url': 'https://pypi.org/project/sampleproject/',
'project_urls': {'Download': 'UNKNOWN',
'Homepage': 'https://github.com/pypa/sampleproject'},
'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
'requires_dist': None,
'requires_python': None,
'summary': 'A sample Python project',
'version': '1.2.0'}
结果可以限定为 深度 (省略号用于更深层的内容)::
>>> pprint.pprint(project_info, depth=1)
{'author': 'The Python Packaging Authority',
'author_email': 'pypa-dev@googlegroups.com',
'bugtrack_url': None,
'classifiers': [...],
'description': 'A sample Python project\n'
'=======================\n'
'\n'
'This is the description file for the project.\n'
'\n'
'The file should use UTF-8 encoding and be written using '
'ReStructured Text. It\n'
'will be used to generate the project webpage on PyPI, and '
'should be written for\n'
'that purpose.\n'
'\n'
'Typical contents for this file would include an overview of '
'the project, basic\n'
'usage examples, etc. Generally, including the project '
'changelog in here is not\n'
'a good idea, although a simple "What\'s New" section for the '
'most recent version\n'
'may be appropriate.',
'description_content_type': None,
'docs_url': None,
'download_url': 'UNKNOWN',
'downloads': {...},
'home_page': 'https://github.com/pypa/sampleproject',
'keywords': 'sample setuptools development',
'license': 'MIT',
'maintainer': None,
'maintainer_email': None,
'name': 'sampleproject',
'package_url': 'https://pypi.org/project/sampleproject/',
'platform': 'UNKNOWN',
'project_url': 'https://pypi.org/project/sampleproject/',
'project_urls': {...},
'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
'requires_dist': None,
'requires_python': None,
'summary': 'A sample Python project',
'version': '1.2.0'}
另外,最大字符数 宽度 可以建议。如果无法拆分长对象,将超过指定的宽度::
>>> pprint.pprint(project_info, depth=1, width=60)
{'author': 'The Python Packaging Authority',
'author_email': 'pypa-dev@googlegroups.com',
'bugtrack_url': None,
'classifiers': [...],
'description': 'A sample Python project\n'
'=======================\n'
'\n'
'This is the description file for the '
'project.\n'
'\n'
'The file should use UTF-8 encoding and be '
'written using ReStructured Text. It\n'
'will be used to generate the project '
'webpage on PyPI, and should be written '
'for\n'
'that purpose.\n'
'\n'
'Typical contents for this file would '
'include an overview of the project, '
'basic\n'
'usage examples, etc. Generally, including '
'the project changelog in here is not\n'
'a good idea, although a simple "What\'s '
'New" section for the most recent version\n'
'may be appropriate.',
'description_content_type': None,
'docs_url': None,
'download_url': 'UNKNOWN',
'downloads': {...},
'home_page': 'https://github.com/pypa/sampleproject',
'keywords': 'sample setuptools development',
'license': 'MIT',
'maintainer': None,
'maintainer_email': None,
'name': 'sampleproject',
'package_url': 'https://pypi.org/project/sampleproject/',
'platform': 'UNKNOWN',
'project_url': 'https://pypi.org/project/sampleproject/',
'project_urls': {...},
'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
'requires_dist': None,
'requires_python': None,
'summary': 'A sample Python project',
'version': '1.2.0'}