Python:命令行,sys.argv,"if __name__ == '__main__' "

Python: command line, sys.argv, "if __name__ == '__main__' "

我在 Jupyter 中使用 Python 有一定的经验,但对如何使用命令行一无所知。我有家庭作业的提示——我了解算法的工作原理,但我不知道如何格式化所有内容,以便它按照指定的方式从命令行运行。

提示:

Question 1: 80 points

Input: a text file that specifies a travel problem (see travel-input.txt for the format) and a search algorithm (more details are below).

python map.py [file] [search] should read the travel problem from “file” and run the “search” algorithm to find a solution. It will print the solution and its cost.

search is one of [DFTS, DFGS, BFTS, BFGS, UCTS, UCGS, GBFTS, GBFGS, ASTS, ASGS]

这是我得到的模板:

from search import ... # TODO import the necessary classes and methods
import sys

if __name__ == '__main__':
    
    input_file = sys.argv[1]
    search_algo_str = sys.argv[2]
    
    # TODO implement
    
    goal_node = ... # TODO call the appropriate search function with appropriate parameters
    
    # Do not change the code below.
    if goal_node is not None:
        print("Solution path", goal_node.solution())
        print("Solution cost", goal_node.path_cost)
    else:
        print("No solution was found.")

python map.py [file] [search] 而言,'file' 指的是 travel-input.txt 而 'search' 指的是 DFTS, DFGS, BFTS,... 等等 - 用户-指定的选择。我的问题:

  1. 我应该把我的搜索功能放在哪里?它们应该都在同一代码块中背靠背吗?
  2. 如何让命令行从四或五个字母的代码中识别每个函数?它只是函数的名称吗?如果我只使用这些字母调用它,函数如何接收输入?
  3. 我需要在我的代码中的任何地方引用输入文件吗?
  4. 我将文件保存在何处以便可以从命令行访问它们是否重要 - .py 文件、旅行 -input.txt 等?我试过从命令行访问它们,但没有成功。

感谢您的帮助!

函数定义在 if __name__ == "__main__" 块之前。要 select 正确的功能,您可以将它们放在字典中并使用 four-letter 缩写作为键,即

def dfts_search(...):
    ...

def dfgs_search(...):
    ....

...

if __name__ == "__main__":

    input_file = sys.argv[1]
    search_algo_str = sys.argv[2]
    
    search_dict = {"DFTS": dfts_search, "DFGS": dfgs_search, ...}

    try:
        func = search_dict[search_algo_str]
        result = func(...)
    except KeyError:
        print(f'{search_algo_str} is an unknown search algorithm')

不确定引用是什么意思,但是 input_file 已经引用了输入文件。您将需要编写一个函数来读取文件并处理内容。

文件的位置应该无关紧要。将所有内容放在同一个目录中可能是最简单的。在命令 window 中,只需 cd 到文件所在的目录,然后 运行 分配中描述的脚本。