1

我有以下代码用于从 RabbitMQ 消息队列接收消息:

import pika

HOST = 'localhost'
QUEUE = 'hello'

with pika.BlockingConnection(pika.ConnectionParameters(host=HOST)) as conn:
    with conn.channel() as channel:
        channel.queue_declare(queue=QUEUE)

        result = ''
        def callback(channel, method, properties, body):
            nonlocal result
            result = body
            channel.stop_consuming()

        channel.basic_consume(queue=QUEUE,
                              on_message_callback=callback,
                              auto_ack=True)
        channel.start_consuming()

        print("Recieved '{}'".format(result))

我在声明中遇到SyntaxError: no binding for nonlocal 'result' found错误。我认为,这个答案使用in 的方式完全相同。在这种我不明白的情况下工作正常。为什么这里没有解决方案?nonlocalnonlocalglobalnonlocal

4

0 回答 0