在linux上运行python程序

2024-04-24 22:41:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我对linux和python不太熟悉。我正在学习这个类,它有python上的一个反向索引程序的示例代码。我想知道如何运行和测试代码。这是提供给我的代码。在

这是映射文件的代码。(倒置的_指数_地图.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程序的代码。(倒置的_指数_减少.py)在

^{pr2}$

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

chmod +x inverted_index_map.py

然后我试着用:

./inverted_index_map.py testfilename.txt

但我不确定程序是否在等待键盘上的某种输入。所以我的问题是如何测试这些代码并查看结果?我真的不熟悉python。在


Tags: key代码inpy程序forlenvalue
3条回答

这两个程序是作为命令行工具编写的,这意味着它们从stdin获取输入并显示到stdout。默认情况下,这意味着它们从键盘获取输入并在屏幕上显示输出。在大多数linuxshell中,您可以通过使用<file.txtfile.txt获取输入,并使用>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,输出写到{},您应该尝试运行:

^{pr2}$

您需要将文件作为标准输入传入,如下所示

python inverted_index_map.py < testfilename.txt

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

^{pr2}$

或者

cat testfilename.txt | ./inverted_index_map.py

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

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

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

相关问题 更多 >