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