2016-11-16 6 views
0

map reduceをローカルで実行しています。Map Reduce:.pyファイルにパイプする前に "python"を指定する必要があるのはなぜですか?

私のコマンドラインコマンドは次のようになります。

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

、これは正常に動作します。しかし、私のコマンドは次のようになりますとき:

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

私は次のエラーを取得する:コマンドラインはbashのように私のpythonファイルを読んでいると神託の構文で混乱するので

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

これは理にかなっています。

私が見ているすべてのオンラインの例(例: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 
+0

あなたのPythonスクリプトの先頭でhashbangの行を追加し 'ます。#/ usr/bin/envをpython' –

+0

シェバングと設定された実行ATTRIB' chmodの+ X script.py' – furas

答えて

3

ファイルはそのiterpreterを知らない。 python ./myfileを使用して明示的に指定しています。明示的に定義したくない場合。あなたはファイルの最初の行にshebangと書くことができます。これは基本的にインタープリタのパスです。 Python用、シェバングのようなある:

#!/usr/bin/env python 

又は

#!/usr/local/bin/python 

詳細については、読み取り:1として

shebang wiki

Under Unix-like operating systems, when a script with a shebang is run as a program, the program loader parses the rest of the script's initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script

+0

恐ろしいを追加!ありがとう、完璧に働いた。 – bigmacboy78

関連する問題