2017-09-15 142 views
1

運行python腳本從Google靜態地圖圖像獲取像素點時出錯。我從Google maps - how to get building's polygon coordinates from address? 我使用python2.7當我運行該腳本我沒有得到任何錯誤執行腳本 最初python腳本,但連續運行3-4小時後,我收到以下錯誤連續執行腳本時出現python腳本庫錯誤

Traceback (most recent call last): 
File "pyscript.py", line 19, in <module> 
imgBuildings = io.imread(urlBuildings) 
File "/usr/local/lib/python2.7/dist-packages/skimage/io/_io.py", line 60, in i 
with file_or_url_context(fname) as fname: 
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__ 
return self.gen.next() 
File "/usr/local/lib/python2.7/dist-packages/skimage/io/util.py", line 29, in 
u = urlopen(resource_name) 
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen 
return opener.open(url, data, timeout) 
File "/usr/lib/python2.7/urllib2.py", line 435, in open 
response = meth(req, response) 
File "/usr/lib/python2.7/urllib2.py", line 548, in http_response 
'http', request, response, code, msg, hdrs) 
File "/usr/lib/python2.7/urllib2.py", line 473, in error 
return self._call_chain(*args) 
File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain 
result = func(*args) 
File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default 
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 403: Forbidden 

因爲我是新來的蟒蛇我不知道如何解決它?這是一種緩存問題嗎? 非常感謝幫助。

+0

我在處理從外部源下載的地理位置數據時最近發現了很多。該代碼不夠靈活,無法處理所需的下載問題。你必須把代碼放在一個嘗試中,除非在一天中有這麼一個機會,你會得到一個網絡丟失並丟失一些數據包。這很可能是所有正在發生的事情。在這種情況下,urllib2下載會返回一個異常。所以那是你所看到的錯誤。 –

回答

1

我見過這個問題相當多,它由於間歇性的網絡丟失錯誤。有一個try/catch異常處理的遞歸技巧,可以避免這種情況的發生,即使您的網絡連續數小時無法正常工作。

解釋:您嘗試下載。如果失敗,下載將再次嘗試遞歸重試1/4,1/2,1,2,4,8,...秒後,等待1小時以獲得下一次下載。例如,如果您在一家公司工作,網絡可能在週末停機,但您的代碼只會輪詢1小時(最多),然後在網絡修復後再次恢復。

import time 

def recursiveBuildingGetter(urlBuildings, waitTime=0.25): 

    try: 
    imgBuildings = io.imread(urlBuildings) 
    except: 
    print "Warning: Failure at time %f secs for %s" % (waitTime, str(urlBuildings)) 
    waitTime = waitTime * 2.0 

    if (waitTime > 3600.0): 
     waitTime = 3600.0 
    time.sleep(waitTime) 

    imgBuildings = recursiveBuildingGetter(urlBuilding, waitTime) 
    if (waitTime == 3600.0): 
     waitTime = 0.25 

    return imgBuildings 
+0

非常感謝Eamonn Kenny。這似乎工作。再次感謝。 – Sunil

+0

很高興它的工作和偉大的事情是,你可以使用它來進行任何形式的URL批量下載。 –