为什么这个全局变量在 python 2.7 中没有更新,即使我正在使用 global 关键字?

Why isnt this global variable being updated in python 2.7 even tho I am using the global keyword?

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

我在脚本顶部创建了一个全局变量,并在回调函数中使用了 global 关键字,据我所知,这应该允许我更新脚本顶部的全局变量,但是当我导入'global variable' 从另一个脚本中我得到了 'test' 的原始值,而不是回调函数中 body 的当前值...

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

Importer.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 的值并尝试打印它时,我得到了 'Test' 的最初分配值,而不是我期望的正文内容...

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

非常感谢任何帮助!

导入后,您需要调用 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