Iura Rusu Iura Rusu - 4 years ago 256
Python Question

Python script closes after some iterations

I wrote a piece of code and when I run it goes smooth until it gets to
"czz", I am a beginner and I do not know what is the problem.. If someone could tell me what I am doing wrong. Basically the idea behind this code is to try to find all 3-letters domains available with ".ro"

import urllib2
import urllib
import string

from urllib2 import Request, urlopen, URLError, HTTPError
from string import ascii_lowercase

f = open('3-letters.txt', 'w')

for x in ascii_lowercase:
for y in ascii_lowercase:
for z in ascii_lowercase:
req = Request("http://"+x+y+z+".ro")

response = urlopen(req)
except HTTPError as e:
except URLError as e:
print "bad "+x+y+z


Answer Source

One problem is that you are not closing your connections after you don't need them any longer, you can do that with response.close(). Do that in a finally block to ensure it will always be executed.

    # do stuff
    # do stuff

In addition, here's a better way to generate all the three letter strings than your nested for loops:

>>> from string import ascii_lowercase
>>> from itertools import product
>>> three_letters = (''.join(x) for x in product(ascii_lowercase, repeat=3))
>>> for x in three_letters:
...     print(x)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download