KeyError: SPARK_HOME during SparkConf initialization

KeyError: SPARK_HOME during SparkConf initialization

我是 spark 新手,我想从命令行 运行 Python 脚本。我已经交互式地测试了 pyspark 并且它有效。尝试创建 sc:

时出现此错误
File "test.py", line 10, in <module>
    conf=(SparkConf().setMaster('local').setAppName('a').setSparkHome('/home/dirk/spark-1.4.1-bin-hadoop2.6/bin'))
  File "/home/dirk/spark-1.4.1-bin-hadoop2.6/python/pyspark/conf.py", line 104, in __init__
    SparkContext._ensure_initialized()
  File "/home/dirk/spark-1.4.1-bin-hadoop2.6/python/pyspark/context.py", line 229, in _ensure_initialized
    SparkContext._gateway = gateway or launch_gateway()
  File "/home/dirk/spark-1.4.1-bin-hadoop2.6/python/pyspark/java_gateway.py", line 48, in launch_gateway
    SPARK_HOME = os.environ["SPARK_HOME"]
  File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'SPARK_HOME'

这里好像有两个问题。

第一个是您使用的路径。 SPARK_HOME 应该指向 Spark 安装的根目录,所以在你的情况下它应该是 /home/dirk/spark-1.4.1-bin-hadoop2.6 而不是 /home/dirk/spark-1.4.1-bin-hadoop2.6/bin.

第二个问题是你如何使用setSparkHome。如果你勾选 a docstring 它的目标是

set path where Spark is installed on worker nodes

SparkConf 构造函数假定 master 上的 SPARK_HOME 已经设置。 It calls pyspark.context.SparkContext._ensure_initialized which calls pyspark.java_gateway.launch_gateway, which tries to acccess SPARK_HOME 失败。

要解决这个问题,您应该在创建 SparkConf 之前设置 SPARK_HOME

import os
os.environ["SPARK_HOME"] = "/home/dirk/spark-1.4.1-bin-hadoop2.6"
conf = (SparkConf().setMaster('local').setAppName('a'))