【问题标题】:Python PrettyPrinter shows object address but not the contentsPython PrettyPrinter 显示对象地址但不显示内容
【发布时间】:2021-05-18 21:15:00
【问题描述】:

我正在尝试通过调用来漂亮地打印一个 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(),正确显示对象数据并格式化?

【问题讨论】:

标签: python pretty-print python-telegram-bot


【解决方案1】:

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()))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多