gpt4 book ai didi

python - 从命令行漂亮地打印 Python 字典

转载 作者:行者123 更新时间:2023-12-02 08:58:01 26 4
gpt4 key购买 nike

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

关于python - 从命令行漂亮地打印 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26935353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com