【问题标题】:Executing a program from the command line in Terminal, and writing the path to two files从终端中的命令行执行程序,并将路径写入两个文件
【发布时间】:2020-12-20 00:10:14
【问题描述】:

我编写了一个程序的三个不同部分(这些部分被命名为 tokenize、countWords 和 printTopMost,它们被放置在一个名为 wordfreq 的文件模块中),它们将组成一个完整的工作程序(我称之为 topmost)。

我希望程序从程序中执行,像这样:

$ python3 topmost.py eng_stopwords.txt examples/article1.txt 20
word                   30
words                  21
count                  11
text                    9
000                     9
counting                7
fiction                 6
novel                   6
rules                   5
length                  5
used                    4
usually                 4
details                 4
software                4
sources                 4
processing              4
segmentation            4
rule                    4
novels                  4
number                  3

在程序名称(最上面)之后是两个文件的路径和一个参数。我想通过导入模块 sys 从程序中访问这些参数(或命令行参数),例如:

import sys

然后指定参数,例如:

sys.argv[1]

这是我一直在写的代码:

import wordfreq
import sys
import urllib.request


def main():
    words = wordfreq.tokenize(open(sys.argv[1]))
    words.close()
    frequencies = wordfreq.countWords(words, str(open(sys.argv[2])).strip('\n'))
    frequencies.close()
    wordfreq.printTopMost(frequencies, sys.argv[3])
    # Close the file with the stop words.

main()

当我运行程序时,它会给出结果:

Erics-MBP:Laboration_1 ericjohannesson$ topmost.py eng_stopwords.txt examples/article.txt 20
bash: topmost.py: command not found

我做错了什么?代码中哪里是问题的原因?

如果您需要有关我正在尝试编写的程序或其他任何内容的更多信息,请随时提出。

【问题讨论】:

    标签: python file command-line-arguments execute sys


    【解决方案1】:

    你没有正确调用 python。

    您需要在命令行调用中插入单词python,以便您的终端知道您正在使用python调用topmost.py文件。

    请注意,我将python 放在$ 之后,但之前 topmost.py

    Erics-MBP:Laboration_1 ericjohannesson$ python topmost.py eng_stopwords.txt examples/article.txt 20
    bash: topmost.py: command not found
    

    【讨论】:

    • 好的,这是否意味着 eng_stopswords.txt 是命令行中的第二个参数,还是仍算作第一个参数?
    • 仍然算第一个。
    猜你喜欢
    • 2018-08-21
    • 2013-12-02
    • 2011-04-29
    • 2010-09-29
    • 2020-07-24
    • 1970-01-01
    • 2016-01-31
    • 2015-04-02
    • 2014-12-15
    相关资源
    最近更新 更多