2017-08-11 81 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=(',', ': '))