Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

Python code to ignore errors

I have a code that stops running each time there is an error. Is there a way to add a code to the script which will ignore all errors and keep running the script until completion?

Below is the code:

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 ['
','
']:
                    if ch in str0:
                        str0 = str0.replace(ch,'')
            str1 = str(tldextract.extract(str0))

            str2 = i.replace('
','') + str1.replace("ExtractResult",":")+'
'
            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)

Many thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should always 'try' to open files. This way you can manage exceptions, if the file does not exist for example. Take a loot at 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

or

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

Do not(!) just 'pass' in the exception block. This will(!) make you fall on your face even harder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...