簡體   English   中英

從命令行漂亮地打印Python字典

[英]Pretty print Python dictionary from command line

我可以從命令行輕松打印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數據結構?

如果您確實需要命令行解決方案,則可以在命令行中使用pprint

$ 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

這個項目是解決這個問題的好方法:

https://github.com/wolever/pprintpp

從自述文件:

$ pip install pprintpp

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM