Hadoop 实战之Streaming(十二)

来源:互联网 发布:miuco淘宝模特 编辑:程序博客网 时间:2024/04/29 18:44

环境:Vmware 8.0 和ubuntu11.04

Hadoop 实战之Streaming(十二)---通过脚本使用Streaming

第一步: 首先在/home/tanglg1987目录下新建一个start.sh脚本文件,每次启动虚拟机都要删除/tmp目录下的全部文件,重新格式化namenode,代码如下:
sudo rm -rf /tmp/*rm -rf /home/tanglg1987/hadoop-0.20.2/logshadoop namenode -formathadoop datanode -formatstart-all.shhadoop fs -mkdir input hadoop dfsadmin -safemode leave

第二步:给start.sh增加执行权限并启动hadoop伪分布式集群,代码如下:

chmod 777 /home/tanglg1987/start.sh./start.sh 

运行过程如下:

第三步:上传本地文件到hdfs

在/home/tanglg1987/input 目录下新建两个文件file01.txt,file02.txt

file01.txt内容如下:

hello hadoop

file02.txt内容如下:

hello world

上传本地文件到hdfs:

hadoop fs -put /home/tanglg1987/file01.txt inputhadoop fs -put /home/tanglg1987/file02.txt input

第四步:新建一个mapper.py和reducer.py的Python文件

mapper.py代码如下:

#!/usr/bin/env pythonimport sys# input comes from STDIN (standard input)for line in sys.stdin:    # remove leading and trailing whitespace    line = line.strip()    # split the line into words    words = line.split()    # increase counters    for word in words:        # write the results to STDOUT (standard output);        # what we output here will be the input for the        # Reduce step, i.e. the input for reducer.py        #        # tab-delimited; the trivial word count is 1        print '%s\\t%s' % (word, 1)

reducer.py代码如下:

#!/usr/bin/env python from operator import itemgetterimport sys # maps words to their countsword2count = {} # input comes from STDINfor line in sys.stdin:    # remove leading and trailing whitespace    line = line.strip()     # parse the input we got from mapper.py    word, count = line.split('\\t', 1)    # convert count (currently a string) to int    try:        count = int(count)        word2count[word] = word2count.get(word, 0) + count    except ValueError:        # count was not a number, so silently        # ignore/discard this line        pass # sort the words lexigraphically;## this step is NOT required, we just do it so that our# final output will look more like the official Hadoop# word count examplessorted_word2count = sorted(word2count.items(), key=itemgetter(0)) # write the results to STDOUT (standard output)for word, count in sorted_word2count:    print '%s\\t%s'% (word, count)

第五步:新建一个test.py的Python文件

解决Linux下运行Python脚本显示“: 没有那个文件或目录”的问题
我猜不少人都遇到过类似的问题:
在Windows下写好了一个python脚本,运行没问题
但放到Linux系统下就必须在命令行前加上一个python解释器才能运行
脚本开头的注释行已经指明了解释器的路径,也用chmod给了执行权限,但就是不能直接运行脚本。
比如这个脚本:
#!/usr/bin/env python
#-*- coding=utf-8 -*-
def main():
print('This is just a test!\r\n')
if __name__ == '__main__':
main()
按理说没错的,但为什么不能直接运行呢?
后来发现问题出在换行表示上……
Windows下,文本的换行是\r\n一同实现的,而*nix下则只用\n
所以我的第一行代码在Linux下就被识别为了:
#!/usr/bin/env python\r
很显然,系统不知道这个"python\r"是个什么东西……
知道了这个,解决方案就很显而易见了,写了一个自动替换换行标志的脚本:

#!/usr/bin/env python#-*- coding=utf-8 -*-import sys, osdef replace_linesep(file_name):if type(file_name) != str:raise ValueErrornew_lines = []#以读模式打开文件try:fobj_original = open(file_name, 'r')except IOError:print('Cannot read file %s!' % file_name)return False#逐行读取原始脚本print('Reading file %s' % file_name)line = fobj_original.readline()while line:if line[-2:] == '\r\n':new_lines.append(line[:-2] + '\n')else:new_lines.append(line)line = fobj_original.readline()fobj_original.close()#以写模式打开文件try:fobj_new = open(file_name, 'w')except IOError:print('Cannot write file %s!' % file_name)return False#逐行写入新脚本print('Writing file %s' % file_name)for new_line in new_lines:fobj_new.write(new_line)fobj_new.close()return Truedef main():args = sys.argvif len(args) < 2:print('Please enter the file names as parameters follow this script.')os._exit(0)else:file_names = args[1:]for file_name in file_names:if replace_linesep(file_name):print('Replace for %s successfully!' % file_name)else:print('Replace for %s failed!' % file_name)os._exit(1)if __name__ == '__main__':main()

第六步:新建一个replace.sh的shell文件

/home/tanglg1987/test/streaming/test.py *.py

运行过程如下:

第七步:编写一个名为:WordCountTest.sh的shell脚本

$HADOOP_HOME/bin/hadoop  jar $HADOOP_HOME/hadoop-0.20.2-streaming.jar -input input -output output -mapper /home/tanglg1987/test/streaming/mapper.py -reducer /home/tanglg1987/test/streaming/reducer.py 

第八步:给WordCountTest.sh增加执行权限并启动脚本,代码如下:

chmod 777 /home/tanglg1987/WordCountTest.sh./WordCountTest

第九步:运行过程如下:

第十步:查看结果集,运行结果如下: