Pretty print Python dictionary from command line

5.6k Views Asked by At

I can pretty print JSON from the command line easily:

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

However it doesn't work for Python dictionaries (obviously):

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

Is there some built-in class I can use similar to json.tool to pretty print Python data structures?

2

There are 2 best solutions below

3
On BEST ANSWER

This project is a nice solution to this problem:

https://github.com/wolever/pprintpp

From the README:

$ pip install pprintpp

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

If you really wanted a command-line solution, you could use the pprint library in a command line:

$ 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']}}

This is easily be wrapped in a module; name this 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()

This'll work exactly like the json.tool module:

echo "..." | python -m pprint_tool