【问题标题】:Pretty print Python dictionary from command line从命令行漂亮地打印 Python 字典
【发布时间】:2015-01-12 03:51:48
【问题描述】:

我可以很容易地从命令行打印 JSON:

$ echo '{"hello": "world"}' |python -mjson.tool
{
    "hello": "world"
}

但是它不适用于 Python 字典(显然):

$ echo "{'hello': None}" |python -mjson.tool
Expecting property name: line 1 column 1 (char 1)

是否有一些我可以使用类似于json.tool 的内置类来漂亮地打印 Python 数据结构?

【问题讨论】:

标签: python dictionary pretty-print


【解决方案1】:

如果你真的想要一个命令行解决方案,你可以在命令行中使用pprint library:

$ echo "{'python': {'hello': [1,2,3,4,42,81,113,256], 'world': ['spam', 'ham', 'eggs', 'bacon', 'eric', 'idle']}}" \
    | python -c 'import sys; from pprint import pprint as pp; pp(eval(sys.stdin.read()))'
{'python': {'hello': [1, 2, 3, 4, 42, 81, 113, 256],
            'world': ['spam', 'ham', 'eggs', 'bacon', 'eric', 'idle']}}

这很容易被封装在一个模块中;将此命名为pprint_tool.py:

import sys
import ast
from pprint import pprint


def main():
    if len(sys.argv) == 1:
        infile = sys.stdin
        outfile = sys.stdout
    elif len(sys.argv) == 2:
        infile = open(sys.argv[1], 'rb')
        outfile = sys.stdout
    elif len(sys.argv) == 3:
        infile = open(sys.argv[1], 'rb')
        outfile = open(sys.argv[2], 'wb')
    else:
        raise SystemExit(sys.argv[0] + " [infile [outfile]]")
    with infile:
        try:
            obj = ast.literal_eval(infile.read())
        except ValueError as e:
            raise SystemExit(e)
    with outfile:
        pprint(obj, outfile)


if __name__ == '__main__':
    main()

这将与json.tool 模块完全相同:

echo "..." | python -m pprint_tool

【讨论】:

  • 为什么不能像 -mjson.tool 一样在 Python 中访问它?这是我想在每个项目中使用的东西,就像 json 打印机一样。
  • @GaborKulcsar:我通常只是打开一个 Python 提示符。我自己并不经常使用这个。随意将其设为feature request。
  • @GaborKulcsar JSON 是一种广泛使用的序列化格式,因此有很多机会可以漂亮地打印它。但是人们多久会格式化一次 Python 输出?
  • 我想如果你有 Python 进程相互通信是有意义的。可能是您无权访问进程本身,但消息被写入日志。而且你可能是最近被分配到这个项目的,所以对 Python 一点都不熟悉……
  • +1 表示ast.literal_eval,没有它,评估是相当不安全的。 JSON 已经有这样的限制,并且在许多语言中都有实现,这都是使用它进行通信的充分理由。 Python 进程经常使用 Pickle 而不是表达式进行通信。
【解决方案2】:

这个项目很好地解决了这个问题:

https://github.com/wolever/pprintpp

来自自述文件:

$ pip install pprintpp

$ echo "{'hello': 'world'}" | pypprint
{'hello': 'world'}

【讨论】:

  • 这个项目如何为这个“问题”提供解决方案?你能至少举一些例子吗?
  • 一个 SO 问题不是宣传第三方库的合适媒介(事实上,问题 “我可以用什么库来做...” 已关闭-话题)。如果这个库确实解决了您的问题,请清楚问题是什么(可能是pprint 的一些特定限制?)以及这个库是如何解决它的。
  • 我不是在做广告,我是在记录我的问题的解决方案(这花了我一些时间谷歌,下次需要 5 秒)。
猜你喜欢
  • 2013-04-12
  • 2020-11-10
  • 2013-12-14
  • 2011-03-14
  • 2016-02-06
  • 2022-11-18
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
相关资源
最近更新 更多