Command-line interface

Now, let's get back to the first issue. Essentially, we need to define a command line
interface (CLI) for our script. There are a few packages for building complex CLIs, but for a
simple one we can use the built-in argparse library. Let's design our interface so that we'll be able to pass the address from the shell:

python geocoder.py --address 'Kremlin, Moscow, Russia'

For that, we need to import the library and create a parser to parse the commands we call. We can add both to the beginning of the script:

import argparse
parser=argparse.ArgumentParser()

As a next step, we need to register the arguments we want to pass in with the parser object, using the add_argument method, and passing the argument name (usually beginning with a double dash) and a help test—it will be printed via the --help command provided by argparse. We can also pass a default value, which will be used if no value is passed:

parser.add_argument("--address", help=“address to search for", default="13 Rue de la Chapelle, 70250 Ronchamp, France")

Once arguments are registered, we can parse them—and use the results in the code. Arguments will be stored as resulting object properties, returning None if the argument wasn't specified and no default value is defined:

args=parser.parse_args()
print(nominatim_geocode(address=args.address))

Now, this script can be used as a standalone tool whenever you need to geocode anything. Perfect!

There are plenty of options for improvement—for example, we could add an interface to run geocoding in bulk, using the given CSV file as a source, and storing the results in another file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset