IndexError:列表索引超出范围Python参数输入

时间:2013-10-10 06:57:28

标签: python

import sys
#print sys.argv[1]
def IndexSearchString():


    This function search a string in a file through index and gives the result.



    #fieldindex = int(sys.argv[1])-1
    stringsrch = sys.argv[2]
    #size = len(sys.argv)
    file_name = open("passwd", "r")
    #print "No of Argu ", size
    ''' 
    if sys.argv[1] == Null:
        print "Please enter argument"   
    '''
    if sys.argv[1].isdigit():
        fieldindex = int(sys.argv[1])-1
    else:
        print "Enter integer in 1st Argument"
        sys.exit(1)
    fieldindex = int(sys.argv[1])-1

    stringsrch = sys.argv[2]

    if len(sys.argv) > 3 :
        print "Enter two arguments only"
        sys.exit(1)

    for store_file in file_name:
        temp = store_file.split(":")
        search = temp[fieldindex]
        #print search 

        if stringsrch in search:
            print store_file

IndexSearchString()
    '''
    My Question is:
    I am taking two argument in the command line. Now I want to handle when only one     argument is given and also when no argument is given.
    Help me out 

    Error:
    Command Window Input: python SearchString.py 1 
    Traceback (most recent call last):
    File "SearchString.py", line 46, in <module>
    IndexSearchString() 
    File "SearchString.py", line 36, in IndexSearchString
    stringsrch = sys.argv[2]
    IndexError: list index out of range
    '''

4 个答案:

答案 0 :(得分:0)

stringsrch = sys.argv [2]

应该是这个

stringsrch = sys.argv [1]

因为你没有其他地方使用

sys.argv中[2]

答案 1 :(得分:0)

你的意见中的

:你应该在sys.argv

中以0开头

答案 2 :(得分:0)

检查这个问题,看看它是否有用 python and sys.argv
在你的“def ...”之后加上这个

if len(sys.argv) < 3 :
  print "Please enter two arguments"
  sys.exit(1)

并改变你的另一个

if len(sys.argv) > 3 :
        print "Enter two arguments only"
        sys.exit(1)

if len(sys.argv) > 4 :
        print "Enter only two arguments after the program"
        sys.exit(1)

更容易

if len(sys.argv) >= 0 | len(sys.argv) < 3 :
  fieldindex = int(sys.argv[1])-1  
else:
  sys.exit("enter up to 2 args")

答案 3 :(得分:0)

不要重新发明轮子,而是使用现有的python命令行参数解析器之一: