1

在 Python Shell 和 BPython 中,我都试图让我的输出自然地分成多行,就像它在节点解释器中所做的那样。

这是我的意思的一个例子:

# 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'}

这将使阅读内容变得更容易。有谁知道是否可以在 BPython 或普通 shell 中配置它?(或者老实说,任何解释器——我都会切换到任何让我这样做的地方。)

非常感谢!

编辑:感谢大家的回答!我以前遇到过 Pretty Print 并考虑过使用它。我还考虑过只使用 for 循环在自己的行上打印所有内容。这些想法不错,但我希望我可以让解释器自动完成。

4

2 回答 2

4

你可以使用pprint()

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

from pprint import pprint
pprint(rd)

结果:

{'accept-ranges': 'bytes',
 'another item': 'another value',
 'cache-control': 'max-age=604800',
 'status': '200'}
于 2017-08-11T00:12:35.400 回答
0

有几种方法可以做到这一点。您可以使用链接中显示的三引号 (""") 以及 "\n"。链接中还列出了其他方法作为 stringl Pythonic 方式来创建长多行字符串。如果处理 Json 对象您可以使用以下代码,这应该会有所帮助。

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=(',', ': '))
于 2017-08-11T00:17:35.117 回答