【问题标题】:How to format output in the Python shell to be multiline? [duplicate]如何将 Python shell 中的输出格式化为多行? [复制]
【发布时间】:2017-08-11 00:11:23
【问题描述】:

在 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 循环在自己的行上打印所有内容。这些想法不错,但我希望我可以让解释器自动完成。

【问题讨论】:

  • 您能否更具体地说明您想要触发换行符的内容?字典中的每个键/值对?任何分隔序列?
  • @BradSolomon:我希望列表或字典中的每个条目都在自己的行中。因此键和值将共享一行,但在列表中,每个条目将在其自己的行上。 Node 会这样做,至少对于中等大小和更长的字典。
  • 你试过 IPython 吗?默认情况下,它具有漂亮的打印效果。
  • 是的,Ipython 似乎是要走的路。应该想出一个单独的!

标签: python python-3.x shell bpython


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    有几种方法可以做到这一点。您可以使用链接中显示的三引号 (""") 以及 "\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=(',', ': '))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多