Question

I'm not a programmer, so very dumb Python question here.

So, I have a script that bulk-check whois information for a list of domains. Here's a small example to show my problem:

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

The output of the script using a valid domain is:

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...

My goal is:

  • When do_whois() function fails (because of an invalid domain for example), whois_loop() should continue from beggining with next domain.

What I don't understand:

  • Why while_loop() seems to continue execution after w = do_whois(domain) line when there is an exception on do_whois() function? Because it's printing out 'Ending loop here...' without the 'Starting loop here...', but I don't understand why is this happening. The while loop shouldn't reach that line if there is an exception (but of course I'm wrong).

I could solve this putting an if condition on the while_loop() for example:

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

That would print:

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

Or other ways, but what I'm trying to understand here is why what I'm doing is wrong? I obviously missing something.

I've read some similar questions and external resources but didn't find a clear explanation of why what I'm trying to do doesn't work.

Thanks!

Was it helpful?

Solution

When you get an error, you call whois_loop() again from inside do_whois, which means you can end up several recursive calls deep, hence the multiple "Ending loop here...". This is unnecessary. The loop will continue once do_whois returns, whether or not you have handled an error inside it (indeed, the point of handling the error "quietly" inside the function is that the calling function doesn't have to know about it).

Instead, try:

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

(Note that it is good practice to have as little as possible in try; the else part runs if no error is raised, so you can continue there.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top