Skip to content

Commit

Permalink
#114 Fixing piping issue & refactored CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
DenisCarriere committed Mar 2, 2015
1 parent 64d8617 commit d2c4faa
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 138 deletions.
64 changes: 1 addition & 63 deletions docs/features/Command Line Interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ $ geocode "Ottawa"
Now, suppose you have a file with two lines, which you want to geocode.

```bash
$ geocode `textfile.txt`
$ geocode "textfile.txt"
{"status": "OK", "locality": "Ottawa", ...}
{"status": "OK", "locality": "Boston", ...}
```
Expand All @@ -43,65 +43,3 @@ Parsing a batch geocode to CSV can also be done with `jq`. Build your headers fi
$ echo 'lat,lng,locality' > test.csv
$ geocode cities.txt | jq [.lat,.lng,.locality] -c | jq -r '@csv' >> test.csv
```

Make the output look **--pretty**!

```bash
$ geocode "Ottawa, Ontario" --pretty
{
"status": "OK",
"city": "Ottawa",
"country": "Canada",
"provider": "bing",
"location": "Ottawa Ontario",
"state": "ON",
"bbox": {
"northeast": [
45.77197265625,
-74.90253448486328
],
"southwest": [
45.07920837402344,
-76.4996109008789
]
},
"address": "Ottawa, ON",
"lat": 45.389198303222656,
"lng": -75.68800354003906,
"quality": "PopulatedPlace",
"accuracy": "Rooftop"
}
```

Change the type of output between JSON/GeoJSON

```bash
$ geocode "Ottawa, Ontario" --geojson --pretty
{
"geometry": {
"type": "Point",
"coordinates": [
-75.68800354003906,
45.389198303222656
]
},
"type": "Feature",
"properties": {
"status": "OK",
"city": "Ottawa",
"country": "Canada",
"provider": "bing",
"location": "Ottawa Ontario",
"state": "ON",
"address": "Ottawa, ON",
"quality": "PopulatedPlace",
"accuracy": "Rooftop"
},
"bbox": [
-76.4996109008789,
45.07920837402344,
-74.90253448486328,
45.77197265625
]
}
```
2 changes: 1 addition & 1 deletion geocoder/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
__title__ = 'geocoder'
__author__ = 'Denis Carriere'
__author_email__ = 'carriere.denis@gmail.com'
__version__ = '1.2.0'
__version__ = '1.2.1'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2013-2015 Denis Carriere'

Expand Down
104 changes: 32 additions & 72 deletions geocoder/cli.py
Original file line number Diff line number Diff line change
@@ -1,83 +1,43 @@
import argparse
import fileinput
import itertools
#!/usr/bin/python
# coding: utf8

import click
import json
import geocoder
import sys
from .api import get
import os


providers = ['google', 'bing', 'osm', 'here', 'w3w', 'opencage']
methods = ['geocode', 'reverse', 'elevation', 'timezone']
outputs = ['json', 'osm', 'geojson', 'wkt']

def peek(iterable):
iterator = iter(iterable)
item = next(iterator)
new_iterator = itertools.chain([item], iterator)
return item, new_iterator

@click.command()
@click.argument('location', nargs=-1)
@click.option('--provider', '-p', default='bing', type=click.Choice(providers))
@click.option('--method', '-m', default='geocode', type=click.Choice(methods))
@click.option('--output', '-o', default='json', type=click.Choice(outputs))
def cli(location, provider, method, output):
"Geocode an arbitrary number of strings from Command Line."

def cli():
parser = argparse.ArgumentParser(description="Geocode an arbitrary number"
" of strings from Command Line.")
parser.add_argument('input',
type=str,
nargs="*",
help="Filename(s) or strings to be geocoded")
parser.add_argument('-p', '--provider',
help="provider (choose from: bing,"
"geonames, google, mapquest, nokia, osm, tomtom, "
"geolytica, arcgis, yahoo, ottawa)",
default='bing')
parser.add_argument('-m', '--method',
type=str,
help="Output type (choose from: geocode, reverse)",
default='geocode')
parser.add_argument('-o', '--outfile',
help="Output file (default stdout)",
default=sys.stdout)
parser.add_argument('-t', '--type',
type=str,
help="Output type (choose from: json, osm, geojson)",
default='json')
parser.add_argument('--pretty',
help="Prettify JSON output",
action="store_true")
args = parser.parse_args()
# Read multiple files & user input location
locations = []
for item in location:
if os.path.exists(item):
with open(item, 'rb') as f:
locations += f.read().splitlines()
else:
locations.append(item)

# User input data
if args.input:
# Geocode results from user input
for location in locations:
g = geocoder.get(location.strip(), provider=provider, method=method)
try:
sys.argv = [sys.argv[1]] + args.input
input = fileinput.input()
_, input = peek(input)
click.echo(json.dumps(g.__getattribute__(output)))
except IOError:
input = args.input
else:
print('[ERROR] Please include a location or a <File Path>.\n'
'$ geocode "Ottawa ON\n"'
'$ geocode "textfile.txt"')
sys.exit()

for item in input:
item = item.strip()
g = get(item, provider=args.provider, method=args.method)

# User input output
args.type = args.type.lower()
type_lookup = {
'json': g.json,
'geojson': g.geojson,
'osm': g.osm,
}
if args.type in type_lookup:
output = type_lookup.get(args.type.lower(), '')
else:
print('[ERROR] Please provide a valid type.\n'
'Ex: geojson, osm, json\n'
'$ geocode "Ottawa ON" --type geojson')
# When invalid command is entered a broken pipe error occurs
sys.exit()

# User define Pretty output
if args.pretty:
params = {'indent': 4}
else:
params = {}

args.outfile.write("{}\n".format(json.dumps(output, **params)))
if __name__ == '__main__':
cli()
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
requests>=2.5.3
ratelim>=0.1.6
ratelim>=0.1.6
click>=3.3.0
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# coding: utf8
from setuptools import setup

__version__ = '1.2.0'
__version__ = '1.2.1'
requirements_file = "requirements.txt"
requirements = [pkg.strip() for pkg in open(requirements_file).readlines()]

Expand Down

0 comments on commit d2c4faa

Please sign in to comment.