【问题标题】:Running python program on linux在linux上运行python程序
【发布时间】:2016-06-08 05:14:39
【问题描述】:

我对 linux 和 python 都不是很熟悉。我正在学习这门课,该课程在 python 上具有倒排索引程序的示例代码。我想知道如何运行和测试代码。这是提供给我的代码。

这是映射文件的代码。 (inverted_index_map.py)

import sys
for line in sys.stdin:
    #print(line)
    key, value = line.split('\t', 1)
    for word in value.strip().split():
        if len(word) <=5 and len(word) >= 3:
          print '%s\t%s' % (word, key.split(':', 1)[0]) #what are we emitting?

这是reduce程序的代码。 (inverted_index_reduce.py)

import sys
key   = None
total = ''
for line in sys.stdin:
    k, v  = line.split('\t', 1)

    if key == k:
        total += v.strip() #what are we accumulating?
    else:
        if key:
            print '%s\t%s' % (key, total) #what are we printing?
        key   = k
        total = v

if key:
    print '%s\t%s' % (key, total) #what are we printing?

它不是可执行文件,所以我尝试了

chmod +x inverted_index_map.py

然后我尝试运行程序:

./inverted_index_map.py testfilename.txt

但我不确定程序是否正在等待来自键盘的某种输入或其他东西。所以我的问题是如何测试这段代码并查看结果?我对python真的不熟悉。

【问题讨论】:

    标签: python linux mapreduce inverted-index


    【解决方案1】:

    这两个程序是作为命令行工具编写的,这意味着它们从标准输入获取输入并将其显示到标准输出。默认情况下,这意味着它们从键盘获取输入并在屏幕上显示输出。在大多数 Linux shell 中,您可以通过使用&lt;file.txtfile.txt 获取输入和&gt;file.txt 以将输出写入file.txt 来更改输入的来源和输出的去向。此外,您还可以使用firstcommand | secondcommand 使一个命令的输出成为另一个命令的输入。

    另一个问题是您发布的脚本没有#! (shebang) 行,这意味着您需要使用python inverted_index_map.py 来运行您的程序。

    如果您想使用来自testfilename.txt 的输入运行inverted_index_map.py 并在屏幕上看到输出,您应该尝试运行:

    python inverted_index_map.py <testfilename.txt
    

    要运行inverted_index_map.py,后跟inverted_index_reduce.py,输入来自testfilename.txt,输出写入outputfile.txt,您应该尝试运行:

    python inverted_index_map.py <testfilename.txt | python inverted_index_reduce.py >outputfile.txt
    

    【讨论】:

    • Traceback(最近一次调用最后一次):文件“inverted_index_map.py”,第 6 行,在 键中,value = line.split('\t', 1) ValueError: need more than 1 value to unpack 当我尝试运行您提供的命令时出现此错误。
    • 这是现在调试python程序的问题。您可以将sys.stderr.write(repr(line)) 行放在给出错误的行上方,以查看该行的确切内容(不污染 sys.stdout),或sys.stderr.write(str(line.split('\t', 1))) 以查看您要拆分的内容。
    【解决方案2】:

    您需要使用python 命令运行脚本来调用python 解释器并将路径作为参数传递给您的脚本。看看这篇文章,我认为它会帮助你入门:

    http://pythoncentral.io/execute-python-script-file-shell/

    【讨论】:

    • 那么使用./和使用python命令有什么区别呢?
    • 这缺少“程序是否正在等待来自键盘的某种输入或其他东西”的问题
    【解决方案3】:

    您需要像这样将文件作为标准输入传入

    python inverted_index_map.py < testfilename.txt
    

    或者在python文件前面加上#!/usr/bin/python#!/usr/bin/env python然后chmod +x就可以运行了

    .\inverted_index_map.py < testfilename.txt
    

    或者

    cat testfilename.txt | ./inverted_index_map.py
    

    这是Writing an Hadoop MapReduce Program in Python 推荐的。

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多