2017-08-11 47 views
0

在Python Shell和BPython中,我试图让自己的输出自然地分裂成多行,例如节点解释器。如何将Python shell中的输出格式化为多行?

这里是我的意思的例子:

# 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-loop来打印所有内容。这些都不是坏主意,但我希望我能让翻译自动完成。

+0

你能成为一个更具体一点关于你想触发线突破了每个键/值对的字典中的任何分隔序列 –

+0

@BradSolomon:???我想每个因此键和值会共享一条线,但是在列表中,每个条目都将在它自己的行上,Node会这样做,至少在中等大小的字典和更长的字典中。 –

+0

您是否尝试过IPython?默认情况下,它具有相当的打印效果 –

回答

2

你可以使用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'} 
0

即使世界几个方法可以做到这一点。您可以使用链接中显示的三重引号(“”)和“\ n”。其他方法在链接中也以字符串形式列出 Pythonic way to create a long multi-line string。 如果处理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=(',', ': '))