【发布时间】:2015-07-16 21:31:42
【问题描述】:
我已经编写了一个 python 代码来总结每个 csv 文件的第一列中的所有数字,如下所示:
import os, sys, inspect, csv
### Current directory path.
curr_dir = os.path.split(inspect.getfile(inspect.currentframe()))[0]
### Setup the environment variables
spark_home_dir = os.path.realpath(os.path.abspath(os.path.join(curr_dir, "../spark")))
python_dir = os.path.realpath(os.path.abspath(os.path.join(spark_home_dir, "./python")))
os.environ["SPARK_HOME"] = spark_home_dir
os.environ["PYTHONPATH"] = python_dir
### Setup pyspark directory path
pyspark_dir = python_dir
sys.path.append(pyspark_dir)
### Import the pyspark
from pyspark import SparkConf, SparkContext
### Specify the data file directory, and load the data files
data_path = os.path.realpath(os.path.abspath(os.path.join(curr_dir, "./test_dir")))
### myfunc is to add all numbers in the first column.
def myfunc(s):
total = 0
if s.endswith(".csv"):
cr = csv.reader(open(s,"rb"))
for row in cr:
total += int(row[0])
return total
def main():
### Initialize the SparkConf and SparkContext
conf = SparkConf().setAppName("ruofan").setMaster("spark://ec2-52-26-177-197.us-west-2.compute.amazonaws.com:7077")
sc = SparkContext(conf = conf)
datafile = sc.wholeTextFiles(data_path)
### Sent the application in each of the slave node
temp = datafile.map(lambda (path, content): myfunc(str(path).strip('file:')))
### Collect the result and print it out.
for x in temp.collect():
print x
if __name__ == "__main__":
main()
我想使用 Apache-Spark 使用相同的 python 代码并行化多个 csv 文件的求和过程。我已经完成了以下步骤:
- 我在 AWS 上创建了一个主节点和两个从节点。
- 我已使用 bash 命令
$ scp -r -i my-key-pair.pem my_dir root@ec2-52-27-82-124.us-west-2.compute.amazonaws.com将目录my_dir包括我的 python 代码和 csv 文件上传到集群主节点。 - 我已经登录了我的主节点,并从那里使用 bash 命令
$ ./spark/copy-dir my_dir将我的 python 代码以及 csv 文件发送到所有从节点。 -
我已经在主节点上设置了环境变量:
$ export SPARK_HOME=~/spark$ export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
但是,当我在主节点上运行 python 代码时:$ python sum.py,它显示以下错误:
Traceback (most recent call last):
File "sum.py", line 18, in <module>
from pyspark import SparkConf, SparkContext
File "/root/spark/python/pyspark/__init__.py", line 41, in <module>
from pyspark.context import SparkContext
File "/root/spark/python/pyspark/context.py", line 31, in <module>
from pyspark.java_gateway import launch_gateway
File "/root/spark/python/pyspark/java_gateway.py", line 31, in <module>
from py4j.java_gateway import java_import, JavaGateway, GatewayClient
ImportError: No module named py4j.java_gateway
我对这个错误没有任何想法。另外,我想知道主节点是否会自动调用所有从节点并行运行。如果有人可以帮助我,我真的很感激。
【问题讨论】:
标签: python amazon-web-services apache-spark master-slave