No module named 'pyspark.streaming.kafka'

一、问题描述

spark版本:2.4.7
pyspark版本:3.1.1
直接使用from pyspark.streaming.kafka import KafkaUtils会提示这个错误。

二、解决方法

1、使用新的api
https://stackoverflow.com/questions/61891762/spark-3-x-integration-with-kafka-in-python
https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html

2、 spark 2.4.x 版本继续使用pyspark.streaming.kafka
https://sandeepkattepogu.medium.com/streaming-data-from-apache-kafka-topic-using-apache-spark-2-4-5-and-python-4073e716bdca
因为服务器spark版本为2.4.7,所以考虑使用pyspark.streaming.kafka。如链接中博客所言,需要findspark模块。

import findspark
findspark.init()
from pyspark.streaming.kafka import KafkaUtils

这样就不会报错。
问题:findspark.init()完成了什么功能,使得可以找到pyspark.streaming.kafka
其核心源码如下:

if not spark_home:
    spark_home = find()

if not python_path:
    python_path = os.environ.get("PYSPARK_PYTHON", sys.executable) 

# ensure SPARK_HOME is defined
os.environ["SPARK_HOME"] = spark_home

# ensure PYSPARK_PYTHON is defined
os.environ["PYSPARK_PYTHON"] = python_path

# add pyspark to sys.path
spark_python = os.path.join(spark_home, "python")
try:
    py4j = glob(os.path.join(spark_python, "lib", "py4j-*.zip"))[0]
except IndexError:
    raise Exception(
         "Unable to find py4j, your SPARK_HOME may not be configured correctly"
      )
sys.path[:0] = [spark_python, py4j]

找到了环境变量中的SPARK_HOME/home/software/install/spark-2.4.7-bin-hadoop2.7。同时把SPARK_HOME下面的python目录添加到系统变量中
/home/software/install/spark-2.4.7-bin-hadoop2.7/python
进入到该python目录,可以发现存在pyspark/streaming/kafka.py。ps:spark3.x 对应python目录下没有了kafka.py。
综上所述:通过执行find.init(),系统变量里就有了/home/software/install/spark-2.4.7-bin-hadoop2.7/python,所以该目录下的kafka.py就可以import导入。
这里温习import相关知识:
https://blog.csdn.net/weixin_38256474/article/details/81228492
只要模块保存到了sys.path中,python就可以找到它。

3、降低pyspark版本,旧的pyspark中自带pyspark.streaming.kafka
https://stackoverflow.com/questions/63053460/no-module-named-pyspark-streaming-kafka-even-with-older-spark-version

posted @ 2021-08-24 11:50  木叶流云  阅读(3385)  评论(0编辑  收藏  举报