我正在尝试缩进 pprint 的输出,以便使用 pprint 获得 8 个空格的缩进。我使用的代码是:
import numpy as np
from pprint import pprint
A = np.array([1, 2, 3, 4])
f = open("log.txt", 'w')
n = 2
for i in range(n):
A = A + 1
f.writelines(list(u' \u27B3 - %s\n'.encode('utf-8') % i for i in A))
pprint(globals())
输出
{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
期望的输出
{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_tab.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb659b8b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist...,
'pprint': <function pprint at 0xb6dea48c>}
简而言之,当写入文件或打印时,我需要一个空格缩进pprint
。我试过了
pp = pprint.PrettyPrinter(indent=8)
但它不起作用