忽略错误的Python代码

忽略错误的Python代码,python,Python,我有一个代码,每次出现错误时都会停止运行。 有没有一种方法可以将代码添加到脚本中,从而忽略所有错误并继续运行脚本直到完成 代码如下: import sys import tldextract def main(argv): in_file = argv[1] f = open(in_file,'r') urlList = f.readlines() f.close() destList = []

我有一个代码,每次出现错误时都会停止运行。 有没有一种方法可以将代码添加到脚本中,从而忽略所有错误并继续运行脚本直到完成

代码如下:

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)
非常感谢

无论您的错误发生在哪里,您都可以将其包装在try/except块中

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

您应该始终“尝试”打开文件。例如,如果文件不存在,您可以通过这种方式管理异常。抢夺


不要(!)只在异常块中“传递”。这会(!)让你更难受。

当然,只要使用try/except语句你的错误发生在哪里?我发现“让我们忽略错误,继续努力”的心态非常令人不安。至少你必须对哪些错误可以安全地忽略,哪些错误可以回过头来。换言之:“我想沿着这条路走,我脸朝下摔了,我怎么能忽略疼痛,只是一直移动我的腿,直到走到路的尽头?”–你可能不应该。@deceze:我想开车沿着这条路走,路很不平坦,我驶进了第一个打破悬挂的坑洞,我想继续穿过所有其他坑洞:d这是一个很好的例子,展示了
with
语句:
with open('myfile.txt')作为f:
的用法。请看本教程中的最后一个“”示例。
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()