防止错误停止Python脚本

时间:2013-04-27 01:50:34

标签: python

使用Python 2.6,当我运行远远低于脚本时会发生以下错误:

Traceback (most recent call last):
  File "g.py", line 7, in <module>
    results  = Geocoder.geocode(row[0])
  File "/usr/lib/python2.6/site-packages/pygeocoder.py", line 261, in geocode
    return GeocoderResult(Geocoder.getdata(params=params))
  File "/usr/lib/python2.6/site-packages/pygeocoder.py", line 223, in getdata
    raise GeocoderError(j['status'], url)
pygeocoder.GeocoderError: Error ZERO_RESULTS
Query: http://maps.google.com/maps/api/geocode/json?region=&sensor=false&bounds=&language=&address=%22++A+FAKE+ADDRESS

Python 2.6脚本:

import csv, string
from pygeocoder import Geocoder

with open('file.csv') as goingGeo:
        theSpreadsheet = csv.reader(goingGeo, quotechar=None)
        for row in theSpreadsheet:
                results  = Geocoder.geocode(row[0])
                (lat, long) = results[0].coordinates
                with open('geo_file.csv', 'a') as f:
                        f.write(row[0] + ",")
                        f.write(row[1] + ",")
                        f.write(row[2] + ",")
                        f.write(row[3] + ",")
                        f.write(row[4] + ",")
                        f.write(row[5] + ",")
                        f.write(row[6] + ",")
                        f.write(row[7] + ",")
                        try:
                                f.write(str(lat))
                        except GeocoderError:            
                                pass
                        f.write(",")
                        try:
                                f.write(str(long))
                        except GeocoderError:            
                                pass
                        f.write('\n')

我只是希望脚本能够继续处理错误。

谢谢!

4 个答案:

答案 0 :(得分:1)

你有一个write调用周围的try / except块,这些块不可能抛出GeoCoderError,但是你没有尝试/除了调用geocoder()之外可以(显然)确实抛出那个错误。你可能想要这样的东西:

try:
    results  = Geocoder.geocode(row[0])
    (lat, long) = results[0].coordinates
except GeocoderError:
    (lat, long) = (0.0, 0.0)

答案 1 :(得分:0)

使用try-except-finally语句,如下所示:

try:
    f.write(str(lat))
except GeocodeError:
    pass
finally:
    do_something_else_regardless_of_above

答案 2 :(得分:0)

您使用try: except GeocoderError部分走在正确的轨道上,但它们位于错误的位置。你需要移动它们来包装Geocoder.geocode调用,因为这就是抛出错误:

        for row in theSpreadsheet:
                try:
                        results  = Geocoder.geocode(row[0])
                except GeocoderError:
                        continue
                (lat, long) = results[0].coordinates

另请注意,您需要import来自GeocoderError的{​​{1}}名称。此外,pygeocoder是Python中的关键字,因此我建议为该变量选择一个不同的名称。

答案 3 :(得分:0)

#starting from line 6:
for row in theSpreadsheet:
        try:
            results  = Geocoder.geocode(row[0])
        except:
            pass
#rest of script . . .

您也可以使用“except”来处理特定错误 离。

try:
    results=Geocoder.geocode(row[0])
except GeocodeError:
    #deal with error