[英]How to get the pprint output as string and not printed on stdout?
在 python 3.6.8 中,我希望pprint
的輸出沒有打印到屏幕上(例如stdout
),但我希望該輸出作為變量中的字符串。
我嘗試了以下(完整示例):
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())
但我剛得到一個空字符串。 我期待一個輸出
{'cell_type': 'code',
'execution_count': None,
'metadata': {'collapsed': True, 'trusted': True},
'outputs': []}
反而。
也許有一種更簡單的方法可以在沒有流的情況下實現這一目標?
最后我想比較兩個非常復雜的詞典,看看它們的區別。 我的想法:生成 dict 的字符串版本並進行比較(與 bash diff
類的東西)。
您在閱讀之前沒有移動文件指針。
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())
要不就
print(f.getvalue())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.