命令行输入

时间:2014-04-11 04:27:38

标签: python loops command-line

我试图从命令行提示符中取出一组数字,然后让程序打印回最小的数字,但我一直得到索引错误,说明myArray =(sys.argv [1])已经没有了范围

 import sys
 from List import *

 def main(int,strings):
     myArray = (sys.argv[1])
     strings = myArray(sys.argv[1:])
     numbers = (int,strings)

     smallest = numbers[0]
     for i in range(1,len(numbers),1):
        if(numbers[i] < smallest):
            smallest = numbers[i]
    print ("The smallest number is", smallest)


main

2 个答案:

答案 0 :(得分:1)

不要重新发明方向盘并使用argparse模块。它简单易读:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-l", "--list", nargs='+', type=int)

args = parser.parse_args()
print("The smallest number is %d" % min(args.list))

这是控制台上的内容:

$ python test.py -l 1 2 3 4 5
The smallest number is 1
$ python test.py --list 1 2 3 4 5
The smallest number is 1

答案 1 :(得分:1)

IndexError表示您正在尝试访问不存在的列表元素。 sys.argv列表在元素0中包含脚本的名称,在其他元素中包含命令行参数。因此,如果使用0命令行参数调用脚本,则元素1不会存在。

以下是处理此问题的两种方法:

# Method one: check first:
if len(sys.argv) <= 1:
    sys.exit('You need to call this script with at least one argument')
myArray = (sys.argv[1]) # Why did you add the parenthesis?
...


# Method two: go for it and ask questions later
try:
    myArray = (sys.argv[1])
    ...
except IndexError:
    sys.exit('You need to call this script with at least one argument')
相关问题