URLを複数回フェッチする必要がある小さなクローラーを作成しています。すべてのスレッドを同時に(同時に)実行する必要があります。
私はそれを行うべき小さなコードを書きました。
import thread
from urllib2 import Request, urlopen, URLError, HTTPError
def getPAGE(FetchAddress):
attempts = 0
while attempts < 2:
req = Request(FetchAddress, None)
try:
response = urlopen(req, timeout = 8) #fetching the url
print "fetched url %s" % FetchAddress
except HTTPError, e:
print 'The server didn\'t do the request.'
print 'Error code: ', str(e.code) + " address: " + FetchAddress
time.sleep(4)
attempts += 1
except URLError, e:
print 'Failed to reach the server.'
print 'Reason: ', str(e.reason) + " address: " + FetchAddress
time.sleep(4)
attempts += 1
except Exception, e:
print 'Something bad happened in gatPAGE.'
print 'Reason: ', str(e.reason) + " address: " + FetchAddress
time.sleep(4)
attempts += 1
else:
try:
return response.read()
except:
"there was an error with response.read()"
return None
return None
url = ("http://www.domain.com",)
for i in range(1,50):
thread.start_new_thread(getPAGE, url)
apacheログからは、スレッドが同時に実行されているようには見えません。リクエスト間に少しギャップがあり、ほとんど検出できませんが、スレッドが実際には並列ではないことがわかります。
GILについて読んだことがありますが、C \ C ++コードを呼び出さずにGILをバイパスする方法はありますか?GILでどのようにスレッド化が可能か本当に理解できませんか?Pythonは基本的に、前のスレッドで終了するとすぐに次のスレッドを解釈しますか?
ありがとう。