繁体   English   中英

Python:当发生外部异常时如何正确地继续while循环

[英]Python: how to properly continue a while loop when an external exception occurs

我不是程序员,所以非常愚蠢的Python问题。

所以,我有一个脚本,可以批量检查域列表的whois信息。 这是一个显示我的问题的小例子:

import pythonwhois as whois

domainList = ['aaaa', 'bbbb', 'ccccc', 'example.com']

def do_whois(domain):
    try:
        w = whois.get_whois(domain)
        print 'Everything OK'
        return w
    except:
        print 'Some error...'
        whois_loop()

def whois_loop():
    while domainList:
        print 'Starting loop here...'
        domain = domainList.pop()
        w = do_whois(domain)
        print 'Ending loop here...'

whois_loop()

使用有效域的脚本输出是:

Starting loop here...
Everything OK
Ending loop here...
Starting loop here...
Some error...
Starting loop here...
Some error...
Starting loop here...
Some error...
Ending loop here...
Ending loop here...
Ending loop here...

我的目标是:

  • 当do_whois()函数失败时(例如由于域无效),whois_loop()应继续从下一个域开始。

我不明白的是:

  • 当do_whois()函数有异常时,为什么while_loop()似乎在w = do_whois(domain)行之后继续执行? 因为它打印出'Ending loop here'而没有'Starting loop here',但我不明白为什么会发生这种情况。 如果有异常,while循环不应该到达那一行(但当然我错了)。

我可以解决这个问题,例如在while_loop()上放置if条件:

w = do_whois(domain)
if not w:
    continue
print 'Ending loop here...'

那将打印:

Starting loop here...
Everything OK
Ending loop here...
Starting loop here...
Some error...
Starting loop here...
Some error...
Starting loop here...
Some error...

或者其他方式,但我在这里想要理解的是为什么我所做的是错的? 我显然错过了什么。

我已经阅读了一些类似的问题和外部资源,但没有找到一个明确的解释, 为什么我要做的事情不起作用

谢谢!

当你收到一个错误时,你会再次从do_whois内部调用whois_loop() ,这意味着你可以深度结束几个递归调用,因此多个"Ending loop here..." 这是不必要的。 一旦do_whois返回,循环将继续,无论你是否在其中处理了一个错误(事实上,在函数内“静静地”处理错误的点是调用函数不必知道它)。

相反,尝试:

def do_whois(domain):
    try:
        w = whois.get_whois(domain)  
    except:
        print 'Some error...'
    else:
        print 'Everything OK'
        return w

(请注意,最好在try尽可能少;如果没有引发错误,则else部分会运行,因此您可以继续执行。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM