1

下面是用于从 producer.py 获取消息的函数

def callback(ch, method, properties, body):
result = body.decode()
resp = JSONEncoder().encode(result)
json_resp = json.loads(resp)
print(json_resp)
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.stop_consuming()

这会打印出预期的结果,但我正在寻找的是在回调函数之外获取变量 json_resp 以进行进一步处理

4

2 回答 2

3

制作该变量,global或者您可以将其存储在任何数据库或文件中,您还可以使用 Python 数据结构,如字典、列表初始化函数的外部并相应地附加值。

于 2017-09-13T10:28:10.090 回答
0

您可以在方法结束时使用 json_resp 值。否则,您可以使用 json_resp 作为参数调用函数来执行进一步处理

1)

def callback(ch, method, properties, body):
    result = body.decode()
    resp = JSONEncoder().encode(result)
    json_resp = json.loads(resp)    
    print(json_resp)
    ch.basic_ack(delivery_tag = method.delivery_tag)
    channel.stop_consuming()
    return json_resp


responce = callback(ch, method, properties, body)
print responce

2)

def callback(ch, method, properties, body):
    result = body.decode()
    resp = JSONEncoder().encode(result)
    json_resp = json.loads(resp)    
    print(json_resp)
    ch.basic_ack(delivery_tag = method.delivery_tag)
    channel.stop_consuming()
    my_process_func(json_resp)

您也可以将 var 视为全局变量,如此处所示,是我个人不太喜欢的

于 2017-09-13T10:02:36.820 回答