Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...