Python 使用Rich打印Dict()

Python 使用Rich打印Dict(),python,rich,Python,Rich,我正在尝试使用pythonsrich打印一个dict()。根据我的理解,这应该在不同的行等上输出数据。有点像pprint 但我得到了: >>> from rich import print >>> print(output) {'GigabitEthernet0/1': {'description': '## Connected to leaf-2 ##', 'type': 'iGbE', 'oper_status': 'up', 'phys_addres

我正在尝试使用pythonsrich打印一个
dict()
。根据我的理解,这应该在不同的行等上输出数据。有点像
pprint

但我得到了:

>>> from rich import print
>>> print(output)

{'GigabitEthernet0/1': {'description': '## Connected to leaf-2 ##', 'type': 'iGbE', 'oper_status': 'up', 
'phys_address': '5000.0009.0001', 'port_speed': 'auto speed', 'mtu': 1500, 'enabled': True, 'bandwidth': 1000000, 
'flow_control': {'receive': False, 'send': False}, 'mac_address': '5000.0009.0001', 'auto_negotiate': True, 
'port_channel': {'port_channel_member': False}, 'duplex_mode': 'auto', 'delay': 10, 'accounting': {'other': {'pkts_in':
0, 'chars_in': 0, 'pkts_out': 431258, 'chars_out': 25875480}, 'ip': {'pkts_in': 513383, 'chars_in': 42910746, 
'pkts_out': 471188, 'chars_out': 45342027}, 'dec mop': {'pkts_in': 0, 'chars_in': 0, 'pkts_out': 7163, 'chars_out': 
551551}, 'arp': {'pkts_in': 3845, 'chars_in': 230700, 'pkts_out': 3846, 'chars_out': 230760}, 'cdp': {'pkts_in': 72010,
'chars_in': 18866620, 'pkts_out': 79879, 'chars_out': 31221768}}, 'ipv4': {'10.1.1.5/30': {'ip': '10.1.1.5',  ...

有什么建议吗?

TL;DR如果你的字典不是dict,那么进行显式转换


根据字典的内容,我假设您的
输出
来自网络设备配置,如Cisco IOS,我对这些方面一无所知,也不太清楚您的数据来自何处

您用来获取
输出的模块或脚本可能实际返回了一个名为
dict
的类型

我推测这就是为什么你的文字是彩色的,但没有美化


例如,让我们看看
rich.print
str的作用

来自rich import print的
>>
>>>打印(打印)
这看起来像这样,就像你的一样

请注意,这是在WSL2中运行的xfce4终端,绘制到X410 X-server。一个完全有能力的终端

这看起来确实像普通的dict,但让我们检查一下它实际上是什么:

>>>类型(str.\uuuu dict\uuuu)
>>>从类型导入MappingProxyType
>>>isinstance(str.\uuuu dict\uuuuuuuuuu,映射ProxyType)
真的
>>>isinstance(str.u dict_u,dict)
假的
正如您所看到的,尽管它的输出看起来像一本字典,但它不是

types.MappingProxyType
本质上是一个只读的听写器,它不一定是一个
dict
。像
rich
这样的第三方库的开发人员可能已经忘记了这种类型的存在。如果是这样的话,那么
rich.print
将做内置的
print()
所做的事情:调用
\uuuu repr\uuu
/
\uu str\uuu
——现在只把它当作字符串

我们可以通过传递类似于方法的
\uuu repr\uuu
的字符串来确认此行为,该字符串仍然得到富文本处理

还可以自己创建
MappingProxyType
的实例

>>>从类型导入映射ProxyType
>>>从丰富的进口印刷品
>>>data={f{n}:n表示范围(11)内的n
>>>打印(数据)
{
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10
}
>>>打印(映射ProxyType(数据))
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
'10': 10}
从中可以看到类型如何影响
rich.print
的输出

要修复,只需将
类型.MappingProxyType
转换为
dict

来自rich import print的
>>
>>>打印(笔录(笔录)


这比以前漂亮多了——不包括
\uuu doc\uuuu
值,它是一个字符串,没有任何帮助。

Rich使用有关终端的信息来确定是否在多行上打印内容。你在哪个终端模拟器上运行这个?你可能是在一个“哑”终端上运行这个程序,这个终端没有提供足够的信息。我使用的是VScode。输出是彩色的吗?@felix001所以,你是在VScode终端上运行的?是的,输出是彩色的,是在VScode终端上。这里是Rich author。这个答案可能是正确的。您的
输出可能是类似dict的对象,但不是实际的dict。我怀疑是
UserDict
而不是MappingProxy。如果你能
打印(输入(输出))
我们肯定知道。