Search code examples
pythonpython-3.xpprint

How to get the pprint output as string and not printed on stdout?


In python 3.6.8 I want to have the output of a pprint not been printed to the screen (e.g stdout), but I want that output as a string in a variable.

I tried the following (complete example):

import io
import pprint

d = {'cell_type': 'code',
   'execution_count': None,
   'metadata': {'collapsed': True, 'trusted': True},
   'outputs': []
}
f = io.StringIO()
pprint.pprint(dict, f)
print(f.read())

but I just got an empty string. I was expecting an output

{'cell_type': 'code',
 'execution_count': None,
 'metadata': {'collapsed': True, 'trusted': True},
 'outputs': []}

instead.

Maybe there is an easier way to achieve this without streams?

In the end I want to compare two very complex dictionaries to see their differences. My idea: Generate a string version of the dict and compare that (with something like a bash diff).


Solution

  • You have not moved your file pointer prior to read.

    f = io.StringIO()
    pprint.pprint(d, f) # note: pass d and not dict
    f.seek(0) # move pointer to start of file
    print(f.read())
    

    or just

    print(f.getvalue())