How to format output in the Python shell to be multiline?

696 views Asked by At

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.

2

There are 2 answers

0
Robᵩ On

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'}
0
Lucas Hendren On

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=(',', ': '))