命令行inpu

2024-04-20 05:21:38 发布

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

我试图从命令行提示符接收一组数字,然后让程序打印回最小的数字,但是我不断得到一个索引错误,说myArray=(系统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

Tags: 命令行import程序main系统错误sys数字
2条回答

不要改头换面地使用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

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')

相关问题 更多 >