My first Python script

I have always avoided Python. I am not sure why, but I think it is mostly because of the syntax, with the needed indention. Well, today I wrote my first script, and I actually like the language a little.

I needed to lookup GPS coordinates for a long list of addresses, and didn’t like doing it manually. Using Google’s maps API, I solved the problem with this little script. It reads the addresses from stdin and writes addresss;latitude;longtitude to stdout.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python
 
# Importing modules
import urllib
import json
import sys
 
# Configuration of main URL
URL = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='
 
# Read addresses from stdin
for address in sys.stdin:
    #print "Looking up: " + str(address)
 
    # URL Encode the address
    encoded_address = urllib.quote(address.strip())
    real_url = URL + encoded_address
 
    # Reset buffer
    buffer = ''
 
    # Fetch the json result
    try:
        fh = urllib.urlopen(real_url)
        for line in fh:
            buffer += line
        fh.close
    except Exception:
        print "Ops, caught an exception."
        sys.exit(1)
 
    # Try to de-serialize the json string
    result = json.loads(buffer)
 
    # Check status of result
    if result['status'] == "OK":
        #print "Results looks good, continue"
        for r in result['results']:
            lat = str(r['geometry']['location']['lat'])
            lng = str(r['geometry']['location']['lng'])
            print '%s; lat=%s; lng=%s' % (address.strip(), lat, lng)
 
# Finish
Share

Leave a Reply