Python中finally后的代码没有运行
我正在尝试返回一个数组。
我可以把消息数组打印到控制台上,并且可以看到它在不断填充数据。不过,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
2 个回答
0
我做了以下这些事情:
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
1
这个行为可能有两个原因:
- 循环没有结束(也就是说,
consumer
一直在返回元素) - 代码抛出了一个异常。
在 finally:
这一行之前加上 print('循环结束')
,这样你就可以知道循环是否结束了。
如果没有结束,那你需要查看 SimpleConsumer
的文档,了解如何检查是否还有更多元素,这样你才能结束循环。
[编辑] 看了一下 SimpleConsumer 的源代码,似乎在没有消息时会有一个超时(默认是 ITER_TIMEOUT_SECONDS
),但代码看起来有点奇怪/坏掉了:如果 iter_timeout 是 None
,那么代码会进入休眠状态,循环就永远不会结束。
所以在创建实例时,试着把 iter_timeout
设置成一个小值,这样循环就应该会停止。