文章目录
- 一、pprint.pprint():美观化打印
- 二、pprint.pformat():格式化成字符串表示
- 三、pprint() 处理包含__repr__() 方法的类
- 四、递归引用:Recursion on {typename} with id={number}
- 五、depth 参数控制 pprint() 方法的输出深度
- 六、width 参数控制 pprint() 方法的输出宽度
- 七、compact 参数尝试在每一行上放置更多数据
pprint
模块包含一个「美观打印机」,用于生成数据结构的美观视图。
本篇文章后续代码中均会使用到如下data
变量数据:
data = [(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),(2, {'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L'}),(3, ['m', 'n']),(4, ['o', 'p', 'q']),(5, ['r', 's', 't''u', 'v', 'x', 'y', 'z']),
]
一、pprint.pprint():美观化打印
使用pprint
模块的pprint()
方法可以美观化打印数据结构。该方法格式化一个对象,并把该对象作为参数传入,写至一个数据流(或者是默认的sys.stdout
)。
from pprint import pprintprint(data)
>>> 输出结果:
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}), (2, {'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H', 'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L'}), (3, ['m', 'n']), (4, ['o', 'p', 'q']), (5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]pprint(data)
>>> 输出结果:
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),(2,{'e': 'E','f': 'F','g': 'G','h': 'H','i': 'I','j': 'J','k': 'K','l': 'L'}),(3, ['m', 'n']),(4, ['o', 'p', 'q']),(5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]
二、pprint.pformat():格式化成字符串表示
使用pprint
模块的pformat()
方法将数据结构格式化成一个字符串表示,然后可以打印这个格式化的字符串或者写入日志。
import logging
from pprint import pformatlogging.basicConfig(# 将日志输出级别设置为 DEBUGlevel=logging.DEBUG,# 日志的输出格式为「级别名称(左对齐8字符)+ 日志消息」,-表示左对齐format='%(levelname)-8s %(message)s',
)logging.debug('Logging pformatted data')
formatted = pformat(data)
for line in formatted.splitlines():logging.debug(line.rstrip())>>> 输出结果:
DEBUG Logging pformatted data
DEBUG [(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
DEBUG (2,
DEBUG {'e': 'E',
DEBUG 'f': 'F',
DEBUG 'g': 'G',
DEBUG 'h': 'H',
DEBUG 'i': 'I',
DEBUG 'j': 'J',
DEBUG 'k': 'K',
DEBUG 'l': 'L'}),
DEBUG (3, ['m', 'n']),
DEBUG (4, ['o', 'p', 'q']),
DEBUG (5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]
三、pprint() 处理包含__repr__() 方法的类
pprint()
方法底层使用的PrettyPrinter
类可以处理定义了__repr__()
方法的类。
from pprint import pprintclass node:def __init__(self, name, contents=[]):self.name = nameself.contents = contents[:]def __repr__(self):# repr()返回一个对象的“官方”字符串表示# 理想情况下,这个字符串是一个有效的 Python 表达式,能够用来重新创建这个对象return ('node(' + repr(self.name) + ', ' +repr(self.contents) + ')')trees = [node('node-1'),node('node-2', [node('node-2-1')]),node('node-3', [node('node-3-1')]),
]
# 嵌套对象的表示形式由 PrettyPrinter 组合,以返回完整的字符串表示
pprint(trees)>>> 输出结果:
[node('node-1', []),node('node-2', [node('node-2-1', [])]),node('node-3', [node('node-3-1', [])])]
四、递归引用:Recursion on {typename} with id={number}
递归数据结构由指向原数据源的引用表示,形式为<Recursion on {typename} with id={number}>
。
from pprint import pprintlocal_data = ['a', 'b', 1, 2]
# 列表增加到其自身,这会创建一个递归引用
local_data.append(local_data)# id()函数用于获取列表对象的内存地址标识符
# 4306287424
print(id(local_data))
# ['a', 'b', 1, 2, <Recursion on list with id=4306287424>]
pprint(local_data)
五、depth 参数控制 pprint() 方法的输出深度
对于非常深的数据结构,可能不必输出所有的细节。使用depth
参数可以控制pprint()
方法对数据结构的输出深度,输出中未包含的层次用省略号表示。
from pprint import pprint# [(...), (...), (...), (...), (...)]
pprint(data, depth=1)
# [(1, {...}), (2, {...}), (3, [...]), (4, [...]), (5, [...])]
pprint(data, depth=2)
六、width 参数控制 pprint() 方法的输出宽度
可以在pprint()
方法中使用参数width
控制格式化文本的输出宽度,默认宽度是80列。注意,当宽度太小而无法完成格式化时,如果截断或转行会导致非法语法,那么便不会截断或转行。
from pprint import pprintfor width in [80, 5, 1]:print('WIDTH =', width)pprint(data, width=width)print()# >>> 输出结果:
WIDTH = 80
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),(2,{'e': 'E','f': 'F','g': 'G','h': 'H','i': 'I','j': 'J','k': 'K','l': 'L'}),(3, ['m', 'n']),(4, ['o', 'p', 'q']),(5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]WIDTH = 5
[(1,{'a': 'A','b': 'B','c': 'C','d': 'D'}),(2,{'e': 'E','f': 'F','g': 'G','h': 'H','i': 'I','j': 'J','k': 'K','l': 'L'}),(3,['m','n']),(4,['o','p','q']),(5,['r','s','tu','v','x','y','z'])]WIDTH = 1
[(1,{'a': 'A','b': 'B','c': 'C','d': 'D'}),(2,{'e': 'E','f': 'F','g': 'G','h': 'H','i': 'I','j': 'J','k': 'K','l': 'L'}),(3,['m','n']),(4,['o','p','q']),(5,['r','s','tu','v','x','y','z'])]
七、compact 参数尝试在每一行上放置更多数据
compact
布尔型参数(默认False
)使得pprint()
方法尝试在每一行上放置更多数据,而不是把复杂数据结构分解为多行。
注意:一个数据结构在一行上放不下时,就会分解;如果多个元素可以放置在一行上,就会合放。
from pprint import pprintprint('DEFAULT:')
pprint(data, compact=False)
print('\nCOMPACT:')
pprint(data, compact=True)>>> 输出结果:
DEFAULT:
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),(2,{'e': 'E','f': 'F','g': 'G','h': 'H','i': 'I','j': 'J','k': 'K','l': 'L'}),(3, ['m', 'n']),(4, ['o', 'p', 'q']),(5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]COMPACT:
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),(2,{'e': 'E','f': 'F','g': 'G','h': 'H','i': 'I','j': 'J','k': 'K','l': 'L'}),(3, ['m', 'n']), (4, ['o', 'p', 'q']),(5, ['r', 's', 'tu', 'v', 'x', 'y', 'z'])]