2个通过python和“如果__name__ ==“ __main__”的命令行输入:“

时间:2018-09-10 21:37:28

标签: python

关于我在做什么错的任何想法?

我正在处理以下代码:

            else:
                stack_queue.append((next, edge + [next]))

if __name__ == "__main__":
    print(list(breath_first_search(graph, 'J', 'A')))

它在Spyder控制台上打印“ [['J','I','H','C','A']]“

我想通过cmd运行它。我正在这样做:

python C:\XX\XX-first-search.py

这也给了我正确的结果。

现在,我想更改它以从cmd接收2个字母的输入。我尝试过:

if __name__ == "__main__":
    print(list(breath_first_search(graph, sys.argv[0], sys.argv[1])))

它给了我错误: error of my first try

我也尝试过:

if __name__ == "__main__":
    print(list(breath_first_search(graph, sys.argv, sys.argv)))

enter image description here

如果需要,请输入我的整个代码:

import sys

graph = {'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'G', 'H']),
         'D': set(['B']),
         'E': set(['B', 'F']),
         'F': set(['E']),
         'G': set(['C']),
         'H': set(['C','I']),
         'I': set(['H', 'J']),
         'J': set(['I'])}


def breath_first_search(graph, initial_node, final_node):
    stack_queue = [(initial_node, [initial_node])]  # List; initial node is the initial node; creates a list 

    while stack_queue:
        (node, edge) = stack_queue.pop(0)

        for next in graph[node] - set(edge):

            if next == final_node:
                yield edge + [next]

            else:
                stack_queue.append((next, edge + [next]))

if __name__ == "__main__":
    print(list(breath_first_search(graph, sys.argv, sys.argv)))

1 个答案:

答案 0 :(得分:3)

sys.argv [doc]是传递给程序的参数列表,包括程序本身作为第一个参数(因此sys.argv[0]是程序的名称)。

因此,我们可以使用sys.argv[1]sys.argv[2]来传递两个额外的参数:

if __name__ == "__main__":
    print(list(breath_first_search(graph, sys.argv[1], sys.argv[2])))

或者我们可以先做一些适当的检查和顺序拆包使其更加美观:

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print('Program requires two parameters')
        sys.exit(1)
    __, a, b = sys.argv
    print(list(breath_first_search(graph, a, b)))