egb*_*kul 2 python dictionary pretty-print
我可以轻松地从命令行打印JSON:
$ echo '{"hello": "world"}' |python -mjson.tool
{
"hello": "world"
}
Run Code Online (Sandbox Code Playgroud)
但它对Python字典不起作用(显然):
$ echo "{'hello': None}" |python -mjson.tool
Expecting property name: line 1 column 1 (char 1)
Run Code Online (Sandbox Code Playgroud)
是否有一些内置类我可以使用类似于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']}}
Run Code Online (Sandbox Code Playgroud)
这很容易包装在一个模块中; 这个名字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()
Run Code Online (Sandbox Code Playgroud)
这个工作就像json.tool模块一样:
echo "..." | python -m pprint_tool
Run Code Online (Sandbox Code Playgroud)