2016-06-09 36 views
-2
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返回到我的外部函數,即getMessage1Python中的內函數

但是這上面的代碼返回我

「功能的onMessage在0x0000000006642128」不是「身體」

,也是我想要得到的出來循環我的內部函數只當uuid存在於body中時。

返回body是一個字符串

這裏要說的是,我使用

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 
+0

請檢查https://stackoverflow.com/help/mcve 您的發佈代碼不完整。 – renemilk

回答

1

爲了getMessage1onMessage返回身體basic_consume功能,你需要返回的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>

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. 我沒有看到在任一功能的迴路。請提供有關問題第二部分的更多信息。

+0

我已經發完整的代碼,請在回答部分 –

+0

SK,我迷路了。你的onMessage函數需要4個參數(通道,方法,屬性和正文)。該功能只使用body。你可以刪除其他3.我不認爲你甚至需要這個函數 - 把邏輯放在循環中。 –

+0

,如果你看一下代碼 self.channel.basic_consume(consumer_callback =的onMessage,隊列= QUEUENAME,NO_ACK = TRUE) 在這裏我使用的接受,所以我有4個參數 –