Python中的内部函数

时间:2016-06-09 15:08:59

标签: python-2.7

def getMessage1(self, id, queueName):

    uuid = id

    def onMessage(ch, method, properties, body):
        if uuid in body:
            requeued_messages = self.channel.stop_consuming()

            return body

    self.channel.basic_consume(consumer_callback = onMessage, queue = queueName, no_ack = True)
    self.channel.start_consuming()
    return onMessage(ch, method, properties, body)
    #global name 'ch' is not defined

我正在尝试定义代码中显示的两个函数。我尝试将body返回到内部函数,我也希望将body返回到我的外部函数,即getMessage1

但是上面的代码返回了

  

"在onMessage上的函数为0x0000000006642128"不是"身体"

并且我希望我的内部函数只有在uuid中存在body时才能从循环中退出。

返回body是一个字符串

这是我正在使用的basic_consume函数

def basic_consume(self, consumer_callback,
                  queue='',
                  no_ack=False,
                  exclusive=False,
                  consumer_tag=None,
                  arguments=None):
    """Sends the AMQP command Basic.Consume to the broker and binds messages
    for the consumer_tag to the consumer callback. If you do not pass in
    a consumer_tag, one will be automatically generated for you. Returns
    the consumer tag.

    For more information on basic_consume, see:
    http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

    :param method consumer_callback: The method to callback when consuming
        with the signature consumer_callback(channel, method, properties,
                                             body), where
                            channel: pika.Channel
                            method: pika.spec.Basic.Deliver
                            properties: pika.spec.BasicProperties
                            body: str, unicode, or bytes

2 个答案:

答案 0 :(得分:1)

要让getMessage1onMessage返回正文,您需要返回onMessage的来电。现在,你正在返回一个功能。

考虑以下两个例子:

def foo():
    def bar():
        return "This is from Bar"
    return bar()

print foo()

结果: This is from Bar

vs

def foo():
    def bar():
        return "This is from Bar"
    return bar

print foo()

结果: <function bar at 0x0270E070>

答案 1 :(得分:0)

  1. 您收到消息function onMessage at 0x0000000006642128,因为您的返回语句return onMessage返回函数onMessage而不评估结果。如果要评估函数,需要使用return onMessage(channel, method, properties, body)之类的函数,并在括号内评估要评估的值/变量。下面是内部和外部函数的工作示例:

    def sumOfSquares(a,b):
        def square(c):
            return (c*c)
        return square(a)+square(b)
    print(sumOfSquares(2,3))
    
  2. 我在两个函数中都没有看到循环。请提供有关问题第二部分的更多信息。