Python代码忽略错误

时间:2015-07-22 12:38:22

标签: python

我有一个代码,每次出现错误时都会停止运行。 有没有办法在脚本中添加代码,忽略所有错误并继续运行脚本直到完成?

以下是代码:

import sys
import tldextract

def main(argv):

        in_file = argv[1]
        f = open(in_file,'r')
        urlList = f.readlines()
        f.close()
        destList = []

        for i in urlList:
            print i
            str0 = i
            for ch in ['\n','\r']:
                    if ch in str0:
                        str0 = str0.replace(ch,'')
            str1 = str(tldextract.extract(str0))

            str2 = i.replace('\n','') + str1.replace("ExtractResult",":")+'\n'
            destList.append(str2)

        f = open('destFile.txt','w')
        for i in destList:
                f.write(i)

        f.close()

        print "Completed successfully:"


if __name__== "__main__":
    main(sys.argv)

非常感谢

2 个答案:

答案 0 :(得分:1)

你应该总是尝试'打开文件。这样,如果文件不存在,您可以管理异常。在Python Tutorial Exeption Handling

处获取战利品
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()

不要(!)只是通过'在异常块中。这会(!)让你更加沮丧。

答案 1 :(得分:0)

如果您的错误发生在哪里,您可以将其包装在try / except块

for i in loop:
    try:
        code goes here...
    except:
        pass