如何阻止python脚本退出错误

时间:2016-09-09 03:06:59

标签: python

我编写了一个小的python脚本,使用pythonwhois对某些域进行批量检查以进行检查。

该脚本从testdomains.txt中读取域并逐个检查它们。然后它将有关域的一些信息记录到results.txt

这是我的剧本:

from time import sleep
import pythonwhois

def lookup(domain):
    sleep(5)
    response = pythonwhois.get_whois(domain)
    ns = response['nameservers']
    return ns


with open("testdomains.txt") as infile:
    domainfile = open('results.txt','w')
    for domain in infile:
        ns = (lookup(domain))
        domainfile.write(domain.rstrip() + ',' + ns+'\n')
    domainfile.close()

当域名未注册或whois服务器由于某种原因未能回复时,我的问题就出现了。脚本退出如下:

Traceback (most recent call last):
  File "test8.py", line 17, in <module>
    ns = lookup(domain)
  File "test8.py", line 9, in lookup
    ns = response['nameservers']
TypeError: 'NoneType' object has no attribute '__getitem__'

我的问题是,我该怎么做才能避免整个脚本退出?

如果出现错误,我希望脚本跳转到下一个域并继续运行而不退出。 将错误记录到results.txt肯定也会很好。

谢谢!

3 个答案:

答案 0 :(得分:4)

您希望使用try/except来使用异常处理。

阅读有关异常处理docker documentation

的文档

获取感兴趣的代码片段,将您的调用包装在try:

for domain in infile:
    try:
        ns = lookup(domain)
    except TypeError as e:
        # should probably use a logger here instead of print
        print('domain not found: {}'.format(e))
        print('Continuing...')
    domainfile.write(domain.rstrip() + ',' + ns+'\n')
domainfile.close()

答案 1 :(得分:0)

with open("testdomains.txt") as infile:
    domainfile = open('results.txt','w')
    for domain in infile:
        try:
            ns = (lookup(domain))
            domainfile.write(domain.rstrip() + ',' + ns+'\n')\
        except TypeError:
            pass
    domainfile.close()

答案 2 :(得分:0)

有两种方法: 1.)要么你可以删除脆弱的代码,以确保没有发生预期。 例如:

from time import sleep
import pythonwhois

def lookup(domain):
    sleep(5)
    response = pythonwhois.get_whois(domain)
    ns = response.get('nameservers')
    return ns


with open("testdomains.txt") as infile:
    domainfile = open('results.txt','w')
    for domain in infile:
        ns = (lookup(domain))
        if ns:
            domainfile.write(domain.rstrip() + ',' + ns+'\n')
    domainfile.close()

2。)优雅地处理异常并让代码继续。如上所述。