您的位置:  首页 » Python » pprint-数据漂亮的打印模块(40)Python语言(必读进阶学习教程)(参考资料)

pprint模块提供了一种“漂亮打印”任意Python数据结构的功能,该形式可用作解释器的输入。如果格式化结构包含非基本Python类型的对象,则表示可能无法加载。如果包含诸如文件,套接字或类之类的对象,以及许多其他不能表示为Python文字的对象,则可能就是这种情况。

如果可以的话,格式化表示将对象保持在单行上,如果它们不适合允许的宽度,则将它们分成多行。PrettyPrinter如果需要调整宽度约束,请显式构造对象。

在计算显示之前,字典按键排序。

pprint模块定义了一个类:

class pprint.PrettyPrinterindent = 1width = 80depth = Nonestream = None*compact = False 
构造一个PrettyPrinter实例。此构造函数了解几个关键字参数。可以使用stream 关键字设置输出流; 流对象上使用的唯一方法是文件协议的 write()方法。如果没有指定,则PrettyPrinter采用 sys.stdout。为每个递归级别添加的缩进量由缩进指定; 默认值为1。其他值可能导致输出看起来有点奇怪,但可以使嵌套更容易发现。可打印的级别数由深度控制; 如果要打印的数据结构太深,则下一个包含的级别将替换为...。默认情况下,对要格式化的对象的深度没有约束。使用width参数约束所需的输出宽度; 默认值为80个字符。如果无法在约束宽度内格式化结构,则将尽最大努力。如果compact为false(默认值),则长序列中的每个项目将在单独的行上进行格式化。如果compact为true,则将在每个输出行上格式化适合宽度的项目。

版本3.4中已更改:添加了compact参数。

>>> 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.pformatobjectindent = 1width = 80depth = None*compact = False 
对象的格式化表示形式返回为字符串。 indent, widthdepthcompactPrettyPrinter 作为格式化参数传递给构造函数。

版本3.4中已更改:添加了compact参数。

pprint.pprintobjectstream = Noneindent = 1width = 80depth = None*compact = False 
上打印对象的格式化表示,然后是换行符。如果是,使用。这可以在交互式解释器中使用,而不是用于检查值的功能(您甚至可以重新分配以在范围内使用)。 indentwidthdepthcompact将作为格式化参数传递给构造函数。Nonesys.stdoutprint()print = pprint.pprintPrettyPrinter

版本3.4中已更改:添加了compact参数。

>>> 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对象

确定对象的格式化表示是否“可读”,或者可以用于使用重构值eval()。这总是返回False 递归对象。

>>> pprint.isreadable(stuff)
False

 

pprint.isrecursive对象
确定对象是否需要递归表示。

还定义了一个支持函数:

pprint.saferepr对象
返回对象的字符串表示形式,以防止递归数据结构。如果对象的表示公开了递归条目,则递归引用将表示为。表示没有以其他方式格式化。<Recursion on typename with id=number>

>>> pprint.saferepr(stuff)
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"

 

PrettyPrinter对象

PrettyPrinter 实例有以下方法:

PrettyPrinter.pformat对象
返回对象的格式化表示。这会考虑传递给PrettyPrinter构造函数的选项。
PrettyPrinter.pprint对象
在配置的流上打印对象的格式化表示,然后是换行符。

以下方法提供相同名称的相应功能的实现。在实例上使用这些方法稍微有效,因为PrettyPrinter不需要创建新对象。

PrettyPrinter.isreadable对象

确定对象的格式化表示是否“可读”,或者可以用于使用重构值eval()。请注意,这将返回 False递归对象。如果设置了深度参数 PrettyPrinter且对象比允许的深,则返回False

PrettyPrinter.isrecursive对象
确定对象是否需要递归表示。

此方法作为钩子提供,以允许子类修改对象转换为字符串的方式。默认实现使用实现的内部 saferepr()

PrettyPrinter.format对象上下文maxlevels级别
返回三个值:作为字符串的对象的格式化版本,指示结果是否可读的标志,以及指示是否检测到递归的标志。第一个参数是要呈现的对象。第二个是字典,其中包含作为id()当前表示上下文的一部分的对象( 影响演示的对象的直接和间接容器)作为键; 如果需要呈现一个已在上下文中表示的对象,则第三个返回值应为True。对该format()方法的递归调用应该为该字典添加容器的附加条目。第三个参数, maxlevels,给出递归所要求的限制; 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'}

 

2 thought on “pprint-数据漂亮的打印模块(40)Python语言(必读进阶学习教程)(参考资料)”

  1. I just wanted to followup on the request I submitted through your contact form a couple weeks ago as I haven’t heard anything back. I pasted it below for your reference.

    Is it okay if we feature your site in our next email newsletter? It’s a perfect fit for a piece we’re doing and I think our audience would find some of the content on your site super useful.

    I know you’re probably busy, so just a simple yes or no would suffice.

    Many Thanks,

评论被关闭。