0

I am trying to create a function to loop through my list of regions and find Longitude and Latitude of them. But the problem is that I am experiencing a timeout problem, hence I want to prompt the system to sleep for about ten seconds and start again. I am not sure how to achieve this in python. I know how to do this in R but in python.

Here is my trial but i dont think this is a correct syntax, not working.

list_of_cities=["Toronto","Chelmsford","San Francisco Bay Area"]

Here is my function:

from geopy.exc import GeocoderTimedOut 
from geopy.geocoders import Nominatim 
import time

def findGeocode(city): 

    repeate(
        geolocator=Nominatim(user_agent="myemail_address@gmail.com")
        return geolocator.geocode(city) 
    
    if (GeocoderTimedOut): 
        time.sleep(10)
    else
        return findGeocode(city))

If this was in R, it would be something like:

repeate{
      res=try(geolocator.geocode(city))
      if(res="try-error)
      {
         sys.sleep(10)
      }
         else 
      {
         break
      }
     }

But not sure how to do this in python.

Can anyone help me with this please?

user86907
  • 817
  • 9
  • 21

1 Answers1

0

You are quite close, since you already implemented it recursively.

def findGeocode(city):
    try: geolocator=Nominatim(user_agent="myemail_address@gmail.com")
    except GeocoderTimedOut:
        sleep(10)
        return findGeocode(city)
    return geolocator.geocode(city)

This would just wait and then call itself until it works.

I am not familiar with geopy and don't really know why you have to wait for 10 seconds, however, you might run into problems since sleep sometimes seems to halt more than you intended (try printing with sleep, without setting flush to True). This would mean that you could run into problems where your program firstly sleeps for a time and then does all at once. In this case you could run the method in another thread.

r0w
  • 155
  • 1
  • 13