---
title: "Using Python to write Hadoop MapReduce program(Reship)"
author: "Data168"
date: "2014-10-11T12:52:37Z"
tags: []
categories: ["编程语言"]
slug: "using-python-to-write-hadoop-mapreduce-program-reship"
draft: false
lastmod: "2014-10-11T12:53:33Z"
id: 2128469
url: "https://data168.iteye.com/blog/2128469"
---

转载自：http://isilic.iteye.com/blog/1750271

 

 

使用 Python 编写 Hadoop MapReduce 程序

 

以前写 Hadoop 的 MapReduce 程序时，使用的是 Java ，利用 Java 写起来是轻车熟路，没有问题，但是使用 Java 很明显的一个弊端就是每次都要编码、打包、上传、执行，还真心是麻烦，想要更加简单的使用 Hadoop 的运算能力，想要写 MapReduce 程序不那么复杂。还真是个问题。

仔细考虑了下，熟悉的 Python 又得拿起来了，随便搜了下 Python 编写 MapReduce 程序，看了个教程，发现用起来真是方便，遂记录之。

 

 

Hadoop 框架使用 Java 开发的，对 Java 进行了原生的支持，不过对于其它语言也提供了 API 支持，如 Python 、C++ 、 Perl 、 Ruby 等。这个工具就是 Hadoop Streaming ，顾名思义， Streaming 就是 Pipe 操作，说起 pipe ，大家肯定不陌生。最原生的 Python 支持是需要 Jython 支持的，不过这里有额外的方法来实现，大家如果只是使用的话，不用纠结 Jython 转换的问题。

 

 

 

前置条件：

Python 环境

Hadoop 环境（ single or cluster ）

 

最容易的 Hadoop 编程模型就是 Mapper 和 Reducer 的编写，这种编程模型大大降低了我们对于并发、同步、容错、一致性的要求，你只要编写好自己的业务逻辑，就可以提交任务。然后喝杯茶，结果就出来了，前提是你的业务逻辑没有错误。

使用 Hadoop Streaming ，能够利用 Pipe 模型，而使用 Python 的巧妙之处在于处理输入输出的数据使用的是 STDIN 和 STDOUT ，然后 Hadoop Streaming 会接管一切，转化成 MapReduce 模型。

 

我们还是使用 wordcount 例子，具体内容不再详细解释，如果有不理解的可以自行度之。下面我们先看下 mapper的代码：

 

Python代码  [![收藏代码](http://isilic.iteye.com/images/icon_star.png)]()

01. #!/usr/bin/env python
02. import sys
03. #input comes from STDIN (standard input)
04. for line in sys.stdin:
05. # remove leading and trailing whitespace
06. line = line.strip()
07. # split the line into words
08. words = line.split()
09. # increase counters
10. for word in words:
11. # write the results to STDOUT (standard output);
12. # what we output here will be the input for the
13. # Reduce step, i.e. the input for reducer.py
14. # tab-delimited; the trivial word count is 1
15. print '%s\\t%s' % (word, 1)

 

简单解释一下，输入从 sys.stdin 进入，然后进行分割操作，对于每行的分割结果，打印出 word 和 count=1， Mapper 就这么简单。

大家看完 Mapper 之后，会产生疑问，这个怎么能够实现 mapper 功能？我们跳出这个 sys.stdin 模型，再回顾下 MapReduce 的程序。在 Mapper 中，程序不关心你怎么输入，只关心你的输出，这个 Mapper 代码会被放到各个 slave 机器上，去执行 Mapper 过程，其实可以理解为过滤、处理。

在示例中，程序的输入会被进行一系列的处理过程，得到 word 和 count ，这个就是 slave 机器上的数据处理之后的内容。仔细理解下这个过程，对于开发程序还是相当有帮助的。

 

下面我们来看下 Reduce 程序， wordcount 的 reduce 程序就是统计相同 word 的 count 数目，然后再输出。我们还是直接上代码吧：

Python代码  [![收藏代码](http://isilic.iteye.com/images/icon_star.png)]()

01. #!/usr/bin/env python
02. from operator import itemgetter
03. import sys
04. current\_word = None
05. current\_count = 0
06. word = None
07. # input comes from STDIN
08. for line in sys.stdin:
09. # remove leading and trailing whitespace
10. line = line.strip()
11. # parse the input we got from mapper.py
12. word, count = line.split('\\t', 1)
13. # convert count (currently a string) to int
14. try:
15. count = int(count)
16. except ValueError:
17. # count was not a number, so silently
18. # ignore/discard this line
19. continue
20. # this IF-switch only works because Hadoop sorts map output
21. # by key (here: word) before it is passed to the reducer
22. if current\_word == word:
23. current\_count += count
24. else:
25. if current\_word:
26. # write result to STDOUT
27. print '%s\\t%s' % (current\_word, current\_count)
28. current\_count = count
29. current\_word = word
30. # do not forget to output the last word if needed!
31. if current\_word == word:
32. print '%s\\t%s' % (current\_word, current\_count)

 

 

看完这个reduce代码，执行一下，完全没有问题，但是未必真正能理解这个reduce的内容，我来解释一下，明确知道执行流程的可以跳过。

reduce的代码页不复杂，利用Reduce程序，可以得出count数目。如果当前的词和分出来的词一致的话，count相加，如果不一致的话，就打印出来，同时更新输入的word和count。最后的if是打印出最后一次统计结果。

reduce的执行依赖了MapReduce模型一个要点，在Shuffle过程中，同一个key会放到同一个reduce任务中，这样处理的是一系列连续的相同的key值，当key不一样的时候，就是说开始统计下一个word了。

&lt;!--EndFragment--&gt;

 

 

利用Python写MapReduce程序就这么多内容，更细节的内容和自己处理的业务相关。

下面测试下结果：

&lt;!--EndFragment--&gt;

Shell代码  [![收藏代码](http://isilic.iteye.com/images/icon_star.png)]()

1. echo "foo foo quux labs foo bar quux" | python ./mapper.py
2. foo     1
3. foo     1
4. quux    1
5. labs    1
6. foo     1
7. bar     1
8. quux    1

 

 进一步可以看到

 

Java代码  [![收藏代码](http://isilic.iteye.com/images/icon_star.png)]()

1. echo "foo foo quux labs foo bar quux" | python ./mapper.py | sort -k1,1 | ./reducer.py
2. bar     1
3. foo     3
4. labs    1
5. quux    2

 

下面就是执行Hadoop命令了，在使用Hadoop Streaming时，要使用一定的格式操作才能提交任务。

&lt;!--EndFragment--&gt; 

 

 

Hadoop代码  [![收藏代码](http://isilic.iteye.com/images/icon_star.png)]()

1. hadoop jar $HADOOP\_HOME/contrib/streaming/hadoop-\*streaming\*.jar –mapper mapperfile –file mapper\_file\_path –reducer reducefile –file reducer\_file\_path –input input\_path –output output\_path

 

将自己的mapper、reducer代码代入上面命令中，执行一下看结果是否正确。

&lt;!--EndFragment--&gt;

 

本文的最后列一下Hadoop Streaming操作的参数，以作备忘。

&lt;!--EndFragment--&gt;

Java代码  [![收藏代码](http://isilic.iteye.com/images/icon_star.png)]()

01. Usage: $HADOOP\_HOME/bin/hadoop jar $HADOOP\_HOME/contrib/streaming/hadoop-streaming.jar \[options]
02. Options:
03. -input    &lt;path&gt;                   DFS input file(s) for the Map step
04. -output   &lt;path&gt;                   DFS output directory for the Reduce step
05. -mapper   &lt;cmd|JavaClassName&gt;      The streaming command to run
06. -combiner &lt;JavaClassName&gt;          Combiner has to be a Java class
07. -reducer  &lt;cmd|JavaClassName&gt;      The streaming command to run
08. -file     &lt;file&gt;                   File/dir to be shipped in the Job jar file
09. -dfs    &lt;h:p&gt;|local                Optional. Override DFS configuration
10. -jt     &lt;h:p&gt;|local                Optional. Override JobTracker configuration
11. -additionalconfspec specfile       Optional.
12. -inputformat TextInputFormat(default)|SequenceFileAsTextInputFormat|JavaClassName Optional.
13. -outputformat TextOutputFormat(default)|JavaClassName  Optional.
14. -partitioner JavaClassName         Optional.
15. -numReduceTasks &lt;num&gt;              Optional.
16. -inputreader &lt;spec&gt;                Optional.
17. -jobconf  &lt;n&gt;=&lt;v&gt;                  Optional. Add or override a JobConf property
18. -cmdenv   &lt;n&gt;=&lt;v&gt;                  Optional. Pass env.var to streaming commands
19. -cacheFile fileNameURI
20. -cacheArchive fileNameURI
21. -verbose

 

下面简单说下参数的意思：

-input：DFS输入，可以有多个input输入，不过我一般喜欢把输入用逗号{,}分割。

-output：DFS输入，实际上就是Reducer输出

-mapper：MapReduce中的Mapper，看清楚了，也可以是cmd shell命令

-combiner：这个必须是Java类

-reducer：MapReducer中的Reducer，也可以是shell命令

-file：这个file参数是用来提交本地的文件，如本地的mapper或者reducer

-dfs：这个是可选的，用来覆盖DFS设定。

-jt：用来覆盖jobtracker的设定

-inputformat：输入格式设定

-outputformat：输出文件的格式设定

 

 

上面的这些参数已经足够平时的应用了，如果有更为细节的需求，就要考虑Streaming是否合适，是否适应自己的业务逻辑。

 

最后再说一句：按照Hadoop Streaming的执行流程，这些参数应该足够了，但是如果我有更复杂的需求：如根据key值分离文件；根据key值重命名文件；读取HDFS上文件配置数据；从多个数据源中读取mapper数据，如HDFS、DataBase、HBase、Nosql等，这些比较灵活的应用使用Python Streaming都有限制，或者是我暂时还没有看到这块。但是目前来说，使用Hadoop Streaming操作能够大量减少代码和流程，比使用Java要方便许多，特别是对于日常的、临时的统计工作。

 

只有更复杂的统计工作和Hadoop Streaming特性，留待以后再行发掘。

&lt;!--EndFragment--&gt;

 

 

&lt;!--EndFragment--&gt;