Hadoop Streaming运行Python脚本程序

1.Streaming简介
Streaming工具允许用户使用非java的语言来编写map和reduce函数。Hadoop的Streaming使用Unix标准作为Hadoop和应用程序之间的接口,所以我们可以使用任何编程语言通过标准输入/输出来写MapReduce程序。详细的用法可以参考这篇博文:  http://dongxicheng.org/mapreduce/hadoop-streaming-programming/。   接下举一个Python脚本编写的WordCount的例子:
2.脚本程序
Mapper:

Reducer:

 
注意脚本程序需要有足够的权限,使用命令:chmod a+x Mapper.py;chmod a+x Reducer.py.
3.测试
在Hadoop集群上运行之前,先在本地测试一下,脚本程序是否可以运行
测试命令:cat test.txt | 'python Mapper.py' | 'python Reducer.py'
我的test.txt内容是:

我的测试结果是:

4.Hadoop集群上运行
首先将test.txt上传到HDFS上,hadoop fs -put test.txt py_input
命令:hadoop jar /usr/local/hadoop/hadoop-1.0.2/contrib/streaming/hadoop-streaming-1.0.2.jar -input py_input -output py_output -mapper 'python Mapper.py' -reducer 'python Reducer.py' -file Mapper.py -file Reducer.py
作业完成之后,查看输出结果:
hadoop fs -cat py_output/part-00000

大功告成!
5.结语
我之前用Hadoop Streaming工具运行了好多次MapReduce程序,Maper,Reducer或是python写的或是shell脚本写的,不过都失败了,出现了各式各样的问题。之前我的运行hadoop作业命令是这样写的:hadoop jar /usr/local/hadoop/hadoop-1.0.2/contrib/streaming/hadoop-streaming-1.0.2.jar -input py_input -output py_output -mapper Mapper.py -reducer Reducer.py -file Mapper.py -file Reducer.py,与上面的命令的区别在于 -mapper部分,如果不添加上python,hadoop streaming并不会执行Mapper.py,Reducer.py,报出IOException错误。所以运行hadoop streaming 作业时一定要确保map、reduce程序运行。
posted @ 2012-10-17 20:06  gerifeng  阅读(2606)  评论(7编辑  收藏  举报