Python PrettyPrinter 显示对象地址但不显示内容

Python PrettyPrinter shows object address but not the contents

我正在尝试通过调用来漂亮地打印一个 python 对象:

from pprint import pprint
...
pprint(update)

但输出看起来像这样:

<telegram.update.Update object at 0xffff967e62b0>

但是,使用 Python 的内部 print() 我得到了正确的输出:

{'update_id': 14191809, 'message': {'message_id': 22222, 'date': 11111, 'chat': {'id': 00000, 'type': 'private', 'username': 'xxxx', 'first_name': 'X', 'last_name': 'Y'}, 'text': '/start', 'entities': [{'type': 'bot_command', 'offset': 0, 'length': 6}], 'caption_entities': [], 'photo': [], 'new_chat_members': [], 'new_chat_photo': [], 'delete_chat_photo': False, 'group_chat_created': False, 'supergroup_chat_created': False, 'channel_chat_created': False, 'from': {'id': 01010101, 'first_name': 'X', 'is_bot': False, 'last_name': 'Y', 'username': 'xxxx', 'language_code': 'en'}}}

有没有办法让 pprint() 正确显示对象数据并格式化?

pprint 使用对象的表示(__repr__() 方法),而 print 使用 __str__()。您在 print 输出中看到的是 不是 字典,而是 telegram.update.Update 实例内部结构的字符串表示形式。

对此没有通用的解决方案,但由于您的问题是关于特定库的,因此咨询 the relevant docs 表明有 .to_json() 方法,因此您可以这样做:

import json
from pprint import pprint

...
pprint(json.loads(update.to_json()))