How to indent with pprint in Python?
Asked Answered
P

3

9

I am trying to indent the output of pprint so that I will get an 8 space indentation with pprint. The code I used is:

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())

Output

{'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>}

Desired output

        {'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>}

In short, I need a space indentation when written to file or printed with pprint. I tried

pp = pprint.PrettyPrinter(indent=8)

but it does not work

Pendragon answered 9/3, 2015 at 8:22 Comment(0)
M
14

You cannot get pprint() to add additional leading indentation, no.

Your best option is to use the pprint.pformat() function instead, then add indentation manually:

from pprint import pformat

print ''.join([
    '        ' + l
    for l in pformat(globals()).splitlines(True)])

This uses the str.splitlines() method to split the pformat() output in to separate lines for ease of re-joining.

In Python 3, indenting can be done with textwrap.indent():

from pprint import pformat
from textwrap import indent

print(indent(pformat(globals()),
             '        '))
Manzanares answered 9/3, 2015 at 8:33 Comment(0)
A
5

I'll probably get jumped on for not directly answering the question within the OP's constraint, but I'd suggest you just use the json library instead of pprint here, viz:

d = {'dog':7,'cat':{'feet':12,'head':7}}
print(json.dumps(d, indent=2))

Yielding

{
   "dog": 7,
   "cat": {
      "feet": 12,
      "head": 7
   }
}

Hat tip Mahmoud Essam.

Airplane answered 22/6, 2022 at 20:36 Comment(0)
D
0

Minor update to Martijn's answer. No need to use .format() where simple str concat will do.

from pprint import pformat

def left_indent(text, indent=' ' * 8):
    return ''.join([indent + l for l in text.splitlines(True)])

print(indent(pformat(data)))
Ditheism answered 22/7, 2018 at 22:37 Comment(3)
You are using a generator expression, not a tuple, which for str.join() is a performance bottleneck. See stackoverflow.com/a/9061024Manzanares
Updated. ------Ditheism
and you're right, not sure why I used format at the time; I think it was a hold over from using .splitlines() without True perhaps (and the format added the newline back).Manzanares

© 2022 - 2024 — McMap. All rights reserved.