1

In both the Python Shell and BPython, I'm trying to make my output naturally break onto multiple lines as it does in, for example, the node interpreter.

Here's an example of what I mean:

# This is what is currently happening 
# (I'm truncating output, but the response is actually a lot longer than this): 
>>> response.dict
{'status': '200', 'accept-ranges': 'bytes', 'cache-control': 'max-age=604800'}

# Here's what I'd like to happen: 
>>> response.dict 
{'status': '200', 
 'accept-ranges': 'bytes', 
 'cache-control': 'max-age=604800'}

This would make reading things A LOT easier. Does anyone know whether or not it's possible to configure this in either BPython or just the plain shell? (Or honestly, any interpreter -- I'd switch to whatever lets me do it.)

Thanks a lot!

EDIT: Thanks for the answers everyone! I've come across Pretty Print before and have considered using it. I've also considered just using a for-loop to print everything on its own line. These aren't bad ideas, but I was hoping that I could get the interpreter to do it automatically.

  • Could you be a bit more specific about what you'd like to trigger a line break? Each key/value pair within a dict? Any delimited sequence? – Brad Solomon Aug 11 '17 at 00:18
  • @BradSolomon: I'd like each entry in a list or dict to go on its own line. So keys and values would share a line, but in a list, each entry would be on its own line. Node does this, at least with mid-sized dicts and longer. – Ian Hoffman Aug 11 '17 at 00:20
  • Have you tried IPython? It has pretty print on by default. – Paulo Almeida Aug 11 '17 at 00:24
  • Yes, Ipython seems to be the way to go. Should have figured that one out solo! – Ian Hoffman Aug 11 '17 at 00:28

2 Answers2

4

You could use pprint():

rd = {'status': '200', 'accept-ranges': 'bytes', 'cache-control': 'max-age=604800', 'another item': 'another value'}

from pprint import pprint
pprint(rd)

Result:

{'accept-ranges': 'bytes',
 'another item': 'another value',
 'cache-control': 'max-age=604800',
 'status': '200'}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

Theres a few ways to do this. You can use triple quotes (""") as shown in the link along with "\n". Other methods are also listed in the link as a stringl Pythonic way to create a long multi-line string. If dealing with a Json object you can use the following code which should help.

import json

with open('msgs.json', 'r') as json_file:
    for row in json_file:
        data = json.loads(row)
        print json.dumps(data, sort_keys=True, indent=2, separators=(',', ': '))
Lucas Hendren
  • 2,786
  • 2
  • 18
  • 33