python代码在finally之后没有运行

python代码在finally之后没有运行,python,Python,我试图返回一个数组 我可以将消息数组打印到控制台,我可以看到它正在填充。 然而,在finally之后的代码似乎是不可访问的。我做错了什么 def kafka_messages(topic, partition): messages = [] try: consumer = SimpleConsumer(kafka, b"consumer-group" , bytes(topic, "UTF-8"

我试图返回一个数组

我可以将消息数组打印到控制台,我可以看到它正在填充。 然而,在finally之后的代码似乎是不可访问的。我做错了什么

def kafka_messages(topic, partition):
    messages = []

    try:
        consumer = SimpleConsumer(kafka, b"consumer-group"
                                  , bytes(topic, "UTF-8")
                                  , partitions=[partition])
        consumer.provide_partition_info()
        consumer.seek(0, 0)

        for message in consumer:
            messages.append(message) # Messages has values

    finally:
        if kafka:
            kafka.close()

    print(messages) # Never even gets run
    return messages

这种行为可能有两个原因:

  • 循环不会终止(即,
    消费者
    不会停止返回元素)
  • 代码抛出一个异常
  • 在最后一行前面添加一个
    print('Loop terminated')
    ,以确定循环是否终止

    如果没有,那么您需要阅读
    SimpleConsumer
    的文档,了解如何检查它是否有更多元素,以便终止循环

    [编辑]查看,当没有消息但代码看起来异常/中断时,似乎有一个超时(默认值为
    ITER\u timeout\u SECONDS
    ),如果
    ITER\u timeout为None
    ,则代码将休眠,循环永远不会终止

    因此,当您创建实例时,尝试将iter\U超时设置为较小的值,循环应该停止。

    以下是我所做的:

    def kafka_messages(topic, partition):
        messages = []
    
        try:
            consumer = SimpleConsumer(kafka, b"consumer-group"
                                      , bytes(topic, "UTF-8")
                                      , partitions=[partition])
            consumer.provide_partition_info()
            consumer.seek(0, 0)
            pending = consumer.pending(partitions=[partition]) # Comes with the API being used
    
            count = 1
            for message in consumer:
                if count == pending:
                    break # Simply break out when you have iterated through all the items
                messages.append(message)
                count += 1
    
        finally:
            if kafka:
                kafka.close()
    
        return messages
    

    kafka.close()的作用是什么?它可能挂着吗?或者,
    消费者
    迭代器可能是无止境的吗?
    消费者
    迭代器似乎是无限的,看起来就像代码中的某个地方,异常正在被吞没。在
    finally:
    之前直接添加
    print()
    语句,以便确保循环终止properly@JohnDoe:好吧,这是你的答案。在调试器中逐步完成。您正在使用调试器,不是吗?SimpleConsumer返回元素计数,我使用它来中断loop@JohnDoe:你也应该发布你的解决方案,否则人们会想知道它是什么。