来自命令行的漂亮的打印Python字典

时间:2014-11-14 17:12:47

标签: python dictionary pretty-print

我可以轻松地从命令行打印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数据结构?

2 个答案:

答案 0 :(得分:5)

如果您真的想要一个命令行解决方案,可以在命令行中使用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()

这&#lll的工作方式与json.tool模块完全相同:

echo "..." | python -m pprint_tool

答案 1 :(得分:-1)

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

https://github.com/wolever/pprintpp

来自自述文件:

$ pip install pprintpp

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