简体   繁体   English

Python-Kafka:程序以交互模式而不是脚本模式运行

[英]Python-Kafka : Program running in interactive mode and not in script mode

I am trying to send some messages to a Kafka topic in Machine_2 through a python script in Machine_1 . 我正在尝试通过Machine_2的python脚本向Machine_1的Kafka主题发送一些消息。 Both Machine_2 and Machine_1 are in the same network and both are VM's in Azure. Machine_2Machine_1都在同一网络中,并且都是Azure中的VM。

Code: sampl.py 代码:sampl.py

from kafka import KafkaProducer
Producer = KafkaProducer(bootstrap_servers=['Machine_2:9092'])
Producer.send('test', 'hello')

If I run the above code as 如果我运行上面的代码为

python sampl.py python sampl.py

There is no messages reaching to the Machine_2 . 没有消息到达Machine_2 However, If I do: 但是,如果我这样做:

python -i sampl.py python -i sampl.py

Then the messages reach to the Machine_2 . 然后消息到达Machine_2 I checked the same using kafka-console-consumer.sh . 我使用kafka-console-consumer.sh进行了检查。 I did yum update in Machine_1 thinking there might be some libraries missing here. 我在Machine_1做了yum update ,认为这里可能缺少一些库。 But no luck yet. 但是还没有运气。

Thanks. 谢谢。

kafka-python maintainer here. kafka-python维护者在这里。 Producer.send('test', b'hello') is asynchronous and does not provide immediate delivery. Producer.send('test', b'hello')是异步的,不提供立即交付。 What you are likely seeing is that the python interpreter is shutting down before the producer has a chance to complete the network send. 您可能会看到,在生产者有机会完成网络发送之前,python解释器已关闭。

If you want to wait until the message is sent before finishing the script, you should use .get(timeout=...). 如果要等到消息发送完成后再执行脚本,则应使用.get(timeout = ...)。 So try: 因此,请尝试:

Producer.send('test', b'hello').get(timeout=1000)

Or alternately, you can call flush() to do the same for all unsent messages: 或者,您可以调用flush()对所有未发送的消息执行相同的操作:

Producer.flush(timeout=1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM