为了用python实现mapreduce,我们先引入下面两个个知识
- sys.stdin()
- itertools之groupby
sys模块的简单学习
sys.stdin 是一个文件描述符,代表标准输入,不需使用open函数打开,就可以使用
例如下面的简单程序
# coding=utf-8
import sys
for line in sys.stdin:
print line
执行命令
cat /etc/passwd | python test_stdin.py
cat 是查看 /etc/passwd 文件内容,然后通过管道符 | 传给python程序,这样就可以一行一行的输出内容了(这里passwd是以一个列表的形式传到了test_stidin.py中了)
延伸学习
>>>sys.stdout.write('hello'+'\n')
hello
#这时屏幕会打印出"hello"字符串(记得还有换行符啊)
那这与Python语言中打印对象调用print obj有什么区别呢,其是事实上就调用了下面的函数sys.stdout.write(obj+"\n")
下面是等价的
1 sys.stdout.write('hello'+'\n')
2
3 print 'hello'
下面我们再来看sys.stdin与raw_input这两个标准输入的区别
当我们使用raw_input(“Input promption:”)时,事实上是先把提示信息输出,然后捕获输入
以下两组在事实上等价:
>>>hi=raw_input('hello? ')
hello?kaixuan #这里是需要从键盘上输入
>>>hi
kaixuan
>>print 'hello? '
hello?
>>>hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream