问题描述
我正在尝试创建一个函数来遍历我的区域列表,并找到它们的经度和纬度。但是问题是我遇到了超时问题,因此我想提示系统休眠约十秒钟,然后重新启动。我不确定如何在python中实现这一点。我知道如何在R中但在python中做到这一点。
这是我的试用版,但我认为这不是正确的语法,无法正常工作。
list_of_cities=["Toronto","Chelmsford","San Francisco Bay Area"]
这是我的功能:
from geopy.exc import GeocoderTimedOut
from geopy.geocoders import Nominatim
import time
def findGeocode(city):
repeate(
geolocator=Nominatim(user_agent="[email protected]")
return geolocator.geocode(city)
if (GeocoderTimedOut):
time.sleep(10)
else
return findGeocode(city))
如果在R中,它将类似于:
repeate{
res=try(geolocator.geocode(city))
if(res="try-error)
{
sys.sleep(10)
}
else
{
break
}
}
但不确定如何在python中执行此操作。
有人可以帮我吗?
解决方法
您已经很接近了,因为您已经递归实现了。
def findGeocode(city):
try: geolocator=Nominatim(user_agent="[email protected]")
except GeocoderTimedOut:
sleep(10)
return findGeocode(city)
return geolocator.geocode(city)
这只会等待,然后自叫,直到工作。
我不熟悉geopy,也不知道为什么要等10秒钟, 但是,您可能会遇到问题,因为睡眠有时似乎会超出您的预期(尝试在睡眠状态下进行打印,而无需将flush设置为True)。这意味着您可能会遇到一些问题,您的程序首先会休眠一段时间,然后立即执行所有操作。在这种情况下,您可以在另一个thread中运行该方法。