在python脚本中没有得到这样的组错误

时间:2017-04-24 04:46:21

标签: python regex

我是python的新手,我试图在脚本下面运行。我收到IO错误没有找到这样的组。如果没有对象,我特别提到不要输入。

非常感谢任何帮助。

ERROR:

T663xt
count value inside if loop  T663xt
 After appending  ['T663xt']
AB12343
count value inside if loop  AB12343
 After appending  ['T663xt', 'AB12343']
None
None
None
Traceback (most recent call last):
  File "./KPHCcommandGenerator.py", line 55, in <module>
    main()
  File "./KPHCcommandGenerator.py", line 51, in main
    F1.ParsingFile ( InputFile )
  File "./KPHCcommandGenerator.py", line 38, in ParsingFile
    print arrayTemp.group( count )
IndexError: no such group

消息来源代码:

#!/usr/bin/python
import os.path
import fileinput
import re


#print "Hello World!!"
class checkingInputFile():
    array   =[] 
    def __init__( self ):
        print "Initializing file class"

    def checkFile ( self, file ):
        self.file = file
        #print ("I am in checkFile "+ file )
        try :
            if os.path.isfile ( self.file ) :
                print ( "File"+ self.file +" exists \n")
            else:
                print "file does not exists"
        except :
            print ( "File " + self.file + "does not exists" )

    def ParsingFile ( self, file ):
        self.file   =   file

        print ( "I am in switch command function" + self.file ) 
        for line in fileinput.input ( self.file ):
            #print ( line )     
            arrayTemp = re.search( r'^ARRAY_SERIAL #,(\w+),(\w+)?,(\w+)?(\w+)?,(\w+)?,.*', line, re.M|re.I )
            if arrayTemp :
                #print ("array lenght " + str(len(arrayTemp.group())) )
                count = 1
                while arrayTemp.group() is not None:
                    print arrayTemp.group( count )
                    #print "count value is ", count
                    if arrayTemp.group( count ) is not None :
                        print "count value inside if loop ",arrayTemp.group( count )
                        checkingInputFile.array.append( arrayTemp.group( count ) )
                        print  " After appending ",checkingInputFile.array
                    count = count + 1
        fileinput.close

def main ():
    InputFile = "/home/pradeep/Documents/Scripts/input.csv"
    F1 = checkingInputFile ()
    F1.checkFile( InputFile )
    F1.ParsingFile ( InputFile )


if __name__ == "__main__":
    main()

正如我们所看到的,我正在尝试迭代我从正则表达式获得的元组。我可能没有值。我只想在我的全局变量中添加非None的值。

1 个答案:

答案 0 :(得分:0)

首先,如果可能,删除或注释掉这个print语句,因为它会在实际工作代码抛出错误之前抛出错误:

print arrayTemp.group( count )

使用try/except块来捕获异常并在超出组范围时很好地处理它:

if arrayTemp.group( count ) is not None :
    try:
        print "count value inside if loop ",arrayTemp.group( count )
        checkingInputFile.array.append( arrayTemp.group( count ) )
        print  " After appending ",checkingInputFile.array
    except IndexError:
        break  # break this while loop
        arrayTemp = None  # breaks out of the outer for loop