简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM