如何将pythonshell中的输出格式化为多行?

2024-06-02 11:12:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在pythonshell和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中配置它?(或者说实话,任何一个口译员——我都会选择让我做的任何事情。)

非常感谢!在

编辑:谢谢大家的回答!我以前见过漂亮的印刷品,考虑过用它。我还考虑过只使用for循环在它自己的行上打印所有内容。这些主意不错,但我希望能让翻译自动完成。在


Tags: cacheagebytes节点isresponsestatuswhat
2条回答

您可以使用^{}

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

from pprint import pprint
pprint(rd)

结果:

^{pr2}$

有几种方法可以做到这一点。您可以使用链接中显示的三引号(“”)和“\n”。其他方法也作为stringl列在链接中 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=(',', ': '))

相关问题 更多 >