0

我有一个回调函数,它在收到每条消息时返回 AMQP 消息的正文。我希望能够将正文的内容分配给一个全局变量,然后在我的程序中进一步使用它。

我在脚本顶部创建了一个全局变量,并在回调函数中使用了 global 关键字,我理解它应该允许我更新脚本顶部的全局变量,但是当我从另一个脚本我从回调函数中返回了'test'的原始值而不是body的当前值......

消费者.py

**python/pika imports and credentials go here**

T_MSG = "test" # create global variable

def main():
    logging.basicConfig()

    (username, password) = open(CREDENTIALS_FILE).read().splitlines()
    credentials = pika.PlainCredentials(username, password)
    params = pika.ConnectionParameters(AMQP_HOST, AMQP_PORT, AMQP_EXCHANGE, credentials)
    connection = pika.BlockingConnection(params)

    channel = connection.channel()

    channel.queue_declare(queue=QUEUE_NAME, durable=False)

    def callback(ch, method, properties, body):
        #print "received message: %r" % body

        global T_MSG # Define that I want to work with the global variable

        #assert isinstance(body, object)

        T_MSG = str(body) # assign the value of body to the global variable 

        print T_MSG # this prints out the body as expected

        return T_MSG
        #ch.basic_ack(delivery_tag = method.delivery_tag)

    #channel.basic_qos(prefetch_count=1)

    channel.basic_consume(callback, queue=QUEUE_NAME, no_ack=False)
    print 'waiting for new messages on queue: '
    channel.start_consuming()

进口商.py

from consumer import T_MSG

print T_MSG # this prints the original value of T_MSG e.g. 'Test'

我不明白为什么 T_MSG 的值没有从回调函数中更新,因为我可以清楚地看到 print 语句正在打印 body 的正确值 - 但即使我在回调函数中将其声明为全局,当我导入 T_MSG 的值并尝试打印它,我得到了最初分配的“测试”值,而不是我期望的正文内容......

我的印象是,每次回调函数接收到一条消息并“处理”它时,应该将 body 的新值分配给 T_MSG (全局)变量,因此我应该能够将它导入到我的 importer.py 脚本中- 但这不起作用,我读过的所有内容都指向在函数中使用 global 关键字来使这个...

任何帮助深表感谢!

4

1 回答 1

0

导入后,您需要调用 consumer.main() 来更改您的变量:

import consumer
print consumer.T_MSG  # here you should see the original value
consumer.main()
print consumer.T_MSG  # now it will be updated
于 2016-12-01T19:40:09.100 回答