本文介绍了Python REPL 中默认的漂亮打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
默认情况下如何在 REPL 上启用漂亮打印?
目前我使用 pprint.pprint()
函数来实现.
但我希望默认打印漂亮
>>>数据{'SHIP_CATEGORY':'','SHIP_QUANTITY': 1,'SHIP_SEPARATELY': 0,'SHIP_SUPPLEMENT': 0,'SHIP_SUPPLEMENT_ONCE': 0,'缩略图':''}我尝试了什么?
我在谷歌上搜索过.没有发现任何大多数结果指向 pprint
模块
解决方案
导入pprint导入系统orig_displayhook = sys.displayhookdef myhook(值):如果值 != 无:__builtins__._ = 值pprint.pprint(值)__builtins__.pprint_on = lambda: setattr(sys, 'displayhook', myhook)__builtins__.pprint_off = lambda: setattr(sys, 'displayhook', orig_displayhook)
把上面的代码放到 PYTHONSTARTUP 如果你不这样做每次运行交互式 shell 时都要输入它.
用法:
>>>数据 = dict.fromkeys(range(10))>>>数据{0:无,1:无,2:无,3:无,4:无,5:无,6:无,7:无,8:无,9:无}>>>pprint_on()>>>数据{0:无,1:无,2:无,3:无,4:无,5:无,6:没有,7:没有,8:没有,9:无}>>>pprint_off()>>>数据{0:无,1:无,2:无,3:无,4:无,5:无,6:无,7:无,8:无,9:无}How can i enable pretty print on the REPL by default?
Currently I do it by using pprint.pprint()
function.
>>> pprint.pprint(data)
{'SHIP_CATEGORY': '',
'SHIP_QUANTITY': 1,
'SHIP_SEPARATELY': 0,
'SHIP_SUPPLEMENT': 0,
'SHIP_SUPPLEMENT_ONCE': 0,
'THUMBNAIL': ''}
But I want pretty print by default
>>> data
{'SHIP_CATEGORY': '',
'SHIP_QUANTITY': 1,
'SHIP_SEPARATELY': 0,
'SHIP_SUPPLEMENT': 0,
'SHIP_SUPPLEMENT_ONCE': 0,
'THUMBNAIL': ''}
What have I tried?
I searched on google. Didn't found anything most result points to pprint
module
解决方案
Use sys.displayhook
import pprint
import sys
orig_displayhook = sys.displayhook
def myhook(value):
if value != None:
__builtins__._ = value
pprint.pprint(value)
__builtins__.pprint_on = lambda: setattr(sys, 'displayhook', myhook)
__builtins__.pprint_off = lambda: setattr(sys, 'displayhook', orig_displayhook)
Put Above code to PYTHONSTARTUP if you don't want type it every time you run interactive shell.
Usage:
>>> data = dict.fromkeys(range(10))
>>> data
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
>>> pprint_on()
>>> data
{0: None,
1: None,
2: None,
3: None,
4: None,
5: None,
6: None,
7: None,
8: None,
9: None}
>>> pprint_off()
>>> data
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
这篇关于Python REPL 中默认的漂亮打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!