Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to indent with pprint in Python?

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

like image 395
Tom Kurushingal Avatar asked Mar 09 '15 08:03

Tom Kurushingal


1 Answers

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()),
             '        '))
like image 199
Martijn Pieters Avatar answered Sep 18 '22 23:09

Martijn Pieters