在 python 鼠兔反应中领先 b

Leading b in python pika response

我正在尝试使用 python 制作一个简单的 AMQP 客户端。我复制了我在 RabbitMQ 网站上找到的代码:

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                  queue='hello',
                  no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

这有效,除了它总是打印类似 [x] Received b'my message' 的内容。因此,我无法解析我的 json 消息。我该如何解决这个问题?

你可以使用 decode() 将字符串转换为 utf-8 然后打印出来,比如

str = 'your str'
print(str.decode())

添加到,我发现你可以将decode()方法直接添加到打印的body var中。像这样:

print(" [x] Received %r" % body.decode())