On this page
pprint —数据漂亮打印机
源代码: Lib/pprint.py
pprint模块提供了一种以可以用作解释器 Importing 的形式“漂亮地打印”任意 Python 数据结构的Function。如果格式化的结构包含不是基本 Python 类型的对象,则表示可能无法加载。如果包括文件,套接字或类之类的对象以及许多其他无法用 PythonLiterals 表示的对象,则可能是这种情况。
如果可以的话,格式化的表示形式会将对象保留在一行上,如果对象超出允许的宽度,则将它们分成多行。如果需要调整宽度约束,则显式构造PrettyPrinter对象。
在计算显示之前,字典按键排序。
pprint模块定义了一个类别:
-
- class *
pprint.
PrettyPrinter
(* indent = 1 , width = 80 , depth = None , stream = None ,**,* compact = False , sort_dicts = True *)
- 构造一个PrettyPrinter实例。该构造函数可以理解几个关键字参数。可以使用* stream 关键字设置输出流;流对象上使用的唯一方法是文件协议的
write()
方法。如果未指定,则PrettyPrinter采用sys.stdout
。为每个递归级别添加的缩进量由 indent 指定;默认值为 1.其他值可能会使输出看起来有些奇怪,但会使嵌套更容易发现。可以打印的级别数由 depth 控制;如果要打印的数据结构太深,则将下一个包含的级别替换为...
。默认情况下,对要格式化的对象的深度没有限制。所需的输出宽度使用 width 参数进行限制;默认值为 80 个字符。如果无法在限制的宽度内格式化结构,则将尽力而为。如果 compact 为 false(默认设置),则长序列的每个项目都将在单独的行上设置格式。如果 compact 为 true,则将在每个输出行上格式化 width 内适合的所有项目。如果 sort_dicts *为 true(默认设置),则将对字典进行格式化并对其键进行排序,否则,它们将以插入 Sequences 显示。
- class *
在版本 3.4 中进行了更改:添加了* compact *参数。
在 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模块还提供了几种快捷Function:
pprint.
pformat
(* object , indent = 1 , width = 80 , depth = None ,**,* compact = False , sort_dicts = True *)- 以字符串形式返回* object *的格式化表示形式。 * indent , width , depth , compact 和 sort_dicts *将作为格式参数传递给PrettyPrinter构造函数。
在版本 3.4 中进行了更改:添加了* compact *参数。
在 3.8 版中进行了更改:添加了* sort_dicts *参数。
pprint.
pp
(* object *, *args , sort_dicts = False , * kwargs *)- 打印* object 的格式表示形式,后跟换行符。如果 sort_dicts *为 false(默认值),则字典将按其插入 Sequences 显示其键,否则将对 dict 键进行排序。 * args 和 kwargs *将作为格式参数传递到pprint()。
3.8 版的新Function。
pprint.
pprint
(* object , stream = None , indent = 1 , width = 80 , depth = None ,**,* compact = False , sort_dicts = True *)- 在* stream 上打印 object 的格式化表示形式,后跟换行符。如果 stream *是
None
,则使用sys.stdout
。可以在交互式解释器中使用它,而不是用于检查值的print()函数(您甚至可以重新分配print = pprint.pprint
以在范围内使用)。 * indent , width , depth , compact 和 sort_dicts *将作为格式参数传递给PrettyPrinter构造函数。
- 在* stream 上打印 object 的格式化表示形式,后跟换行符。如果 stream *是
在版本 3.4 中进行了更改:添加了* compact *参数。
在 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 *)- 确定* object *的格式表示形式是否“可读”,或者可用于使用eval()来重建值。对于递归对象,它总是返回
False
。
- 确定* object *的格式表示形式是否“可读”,或者可用于使用eval()来重建值。对于递归对象,它总是返回
>>> pprint.isreadable(stuff)
False
pprint.
isrecursive
(* object *)- 确定* object *是否需要递归表示。
还定义了另一种支持Function:
pprint.
saferepr
(* object *)- 返回* object 的字符串表示形式,以防止递归数据结构。如果 object *的表示形式公开了递归项,则递归引用将表示为
<Recursion on typename with id=number>
。该表示未进行其他格式化。
- 返回* object 的字符串表示形式,以防止递归数据结构。如果 object *的表示形式公开了递归项,则递归引用将表示为
>>> pprint.saferepr(stuff)
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"
PrettyPrinter Objects
PrettyPrinter个实例具有以下方法:
PrettyPrinter.
pformat
(* object *)- 返回* object *的格式表示。这考虑到传递给PrettyPrinter构造函数的选项。
PrettyPrinter.
pprint
(* object *)- 在配置的流上打印格式为* object *的表示形式,然后换行。
以下方法提供了具有相同名称的相应Function的实现。由于不需要创建新的PrettyPrinter对象,因此在实例上使用这些方法的效率稍高。
PrettyPrinter.
isreadable
(* object *)- 确定对象的格式化表示形式是“可读的”,还是可以使用eval()来重构该值。请注意,这将为递归对象返回
False
。如果设置了PrettyPrinter的* depth *参数,并且对象的深度超出允许范围,则返回False
。
- 确定对象的格式化表示形式是“可读的”,还是可以使用eval()来重构该值。请注意,这将为递归对象返回
PrettyPrinter.
isrecursive
(* object *)- 确定对象是否需要递归表示。
该方法作为一个钩子提供,以允许子类修改将对象转换为字符串的方式。默认实现使用saferepr()实现的内部。
PrettyPrinter.
format
(* object , context , maxlevels , level *)
Example
为了演示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'}
结果可以限制为某个* depth *(Ellipsis号用于更深的内容):
>>> 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'}