问题
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
回答1:
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}
回答2:
Use IPython shell:
In [10]: data = {'SHIP_CATEGORY': '', 'SHIP_QUANTITY': 1, 'SHIP_SEPARATELY': 0, 'SHIP_SUPPLEMENT': 0, 'SHIP_SUPPLEMENT_ONCE': 0,}
In [11]: data
Out[11]:
{'SHIP_CATEGORY': '',
'SHIP_QUANTITY': 1,
'SHIP_SEPARATELY': 0,
'SHIP_SUPPLEMENT': 0,
'SHIP_SUPPLEMENT_ONCE': 0}
It also has an option --no-pprint
in case you want to disable this pretty printing.
IPython
shell also has features like tab-completion, multi-line paste, run shell commands etc. So, it is quite better than the normal python shell.
回答3:
Based on falsetru's accepted answer, but in the form of a one-liner:
from pprint import pprint
import sys
sys.displayhook = lambda x: exec(['_=x; pprint(x)','pass'][x is None])
and to switch back (based on kyrill's comment):
sys.displayhook = sys.__displayhook__
来源:https://stackoverflow.com/questions/17248383/pretty-print-by-default-in-python-repl