【问题标题】:Map Reduce: Why Do I Need to Specify "python" Before Piping to .py File?Map Reduce:为什么我需要在管道到 .py 文件之前指定“python”?
【发布时间】:2017-03-30 01:11:52
【问题描述】:

我正在本地运行 map reduce。

我的命令行命令如下所示:

cat testfile | python ./mapper.py | python ./reducer.py

这很好用。但是,当我的命令看起来像这样时:

cat testfile | ./mapper.py | ./reducer.py

我收到以下错误:

./mapper.py: line 1: import: command not found
./mapper.py: line 3: syntax error near unexpected token `('
./mapper.py: line 3: `def mapper():

这是有道理的,因为命令行正在将我的 python 文件作为 bash 读取并且被 pythonic 语法弄糊涂了。

但是我看到的所有在线示例(例如http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/)都没有在 .py 文件之前包含python。如何配置我的机器运行管道而不在 mapper.pyreducer.py 之前指定 python

以防万一,这是我的映射器代码:

import sys

def mapper():
    for line in sys.stdin:
        data = line.strip().split('\t')
        if len(data) == 6:
            category = data[3]
            sales = data[4]
            print '{0}\t{1}'.format(category, sales)

if __name__ == "__main__":
    mapper()

这是我的减速器代码:

import sys

def reducer():
    current_total = 0
    old_key = None

    for line in sys.stdin:
        data = line.strip().split('\t')
        if len(data) == 2:
            current_key, sales = data
            sales = float(sales)

            if old_key and current_key != old_key:
                print "{0}\t{1}".format(old_key, current_total)
                current_total = 0
            old_key = current_key
            current_total += sales

    print "{0}\t{1}".format(current_key, current_total)

if __name__ == "__main__":
    reducer()

我的数据如下所示:

2012-01-01      09:01   Anchorage       DVDs    6.38    Amex
2012-01-01      09:01   Aurora    Electronics    117.81  MasterCard
2012-01-01      09:01   Philadelphia    DVDs    351.31  Cash

【问题讨论】:

  • 在你的python脚本的开头添加一个hashbang行#!/usr/bin/env python
  • 添加shebang并设置执行属性chmod +x script.py

标签: python bash python-2.7 command-line mapreduce


【解决方案1】:

因为您的文件不知道它的迭代器。您正在使用python ./myfile 明确指定它。如果您不想明确定义它。你可以在文件的第一行提到shebang,这基本上是解释器的路径。对于 Python,shebang 就像:

#!/usr/bin/env python 

#!/usr/local/bin/python

更多信息,请阅读:

根据shebang wiki

在类 Unix 操作系统下,当带有 shebang 的脚本作为程序运行时,程序加载器会将脚本初始行的其余部分解析为解释器指令;而是运行指定的解释器程序,将尝试运行脚本时最初使用的路径作为参数传递给它

【讨论】:

    猜你喜欢
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多