-4

我的命令行参数:

python SearchString.py 10 nee

参数 1 与长度不匹配。我应该如何处理?

错误:文件“SearchString.py”,第 30 行,在 string_search search = temp[fieldindex] IndexError:列表索引超出范围

#!usr/bin/python
import sys

def string_search():
    '''
    This function search a string in a file through index and gives the result.

    :returns: none
    :return type: none 
    :author:XYZ   

    '''
    if len(sys.argv) != 3:
        print "Enter Two Arguments Only"
        sys.exit()

    stringsrch = sys.argv[2]
    found = False
    file_name = open("passwd", "r")

    if sys.argv[1].isdigit():
        fieldindex = int(sys.argv[1])-1
    else:
       print "Enter Integer in 1st Argument"
    sys.exit()
    #fieldindex = int(sys.argv[1])-1

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

        if stringsrch in search:
            print store_file
            found = True
    if not found:
        print "No String "

string_search()
4

1 回答 1

0

我认为代码取决于您如何使用它。 search = temp[fieldindex]. 从代码中,您的 fieldindex 是9,因此您应该确保len(temp) > 9. 否则你会得到你所说的错误。

于 2013-10-11T05:29:49.167 回答