Skip to content

Commit

Permalink
Merge pull request #41 from sbdt-google/master
Browse files Browse the repository at this point in the history
Python3 support.
  • Loading branch information
tylere authored May 3, 2019
2 parents fa3bba4 + bb631d8 commit bb9a3f9
Show file tree
Hide file tree
Showing 25 changed files with 715 additions and 348 deletions.
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
except ImportError:
from distutils.core import setup

version = '0.1.3'
version = '0.2.0'

setup(
name='pykml',
Expand All @@ -21,7 +21,7 @@
],
},
install_requires=[
'lxml>=2.2.6',
'lxml>=3.3.6',
],
tests_require=['nose'],
description="Python KML library",
Expand Down
6 changes: 3 additions & 3 deletions src/examples/KmlReference/altitudemode_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@
)
)

print etree.tostring(doc, pretty_print=True)
print(etree.tostring(doc, pretty_print=True).decode())

# output a KML file (named based on the Python script)
outfile = file(__file__.rstrip('.py')+'.kml','w')
outfile.write(etree.tostring(doc, pretty_print=True))
with open(__file__.rstrip('.py')+'.kml','w') as outfile:
outfile.write(etree.tostring(doc, pretty_print=True).decode())

assert Schema('kml22gx.xsd').validate(doc)

Expand Down
8 changes: 4 additions & 4 deletions src/examples/KmlReference/animatedupdate_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@
)
)

print etree.tostring(doc, pretty_print=True)
print(etree.tostring(doc, pretty_print=True).decode())

# output a KML file (named based on the Python script)
outfile = file(__file__.rstrip('.py')+'.kml','w')
outfile.write(etree.tostring(doc, pretty_print=True))

with open(__file__.rstrip('.py')+'.kml','w') as outfile:
outfile.write(etree.tostring(doc, pretty_print=True).decode())

schema = Schema('kml22gx.xsd')
import ipdb; ipdb.set_trace()
schema.validate(doc)
6 changes: 1 addition & 5 deletions src/examples/Tours/circle_around_landmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,4 @@
# check that the KML document is valid using the Google Extension XML Schema
assert(Schema("kml22gx.xsd").validate(tour_doc))

print etree.tostring(tour_doc, pretty_print=True)

# output a KML file (named based on the Python script)
outfile = file(__file__.rstrip('.py')+'.kml','w')
outfile.write(etree.tostring(tour_doc, pretty_print=True))
print(etree.tostring(tour_doc, pretty_print=True).decode())
6 changes: 3 additions & 3 deletions src/examples/Tours/example_spline_camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,8 @@ def interpolate_location_series(
):
'''Estimate location data structures based on interpolation'''
nKnownPositions = len(known_positions)
x = range(nKnownPositions)
x_new = [1.0*i*(nKnownPositions-1)/number_of_positions for i in range(number_of_positions)]
x = list(range(nKnownPositions))
x_new = [(1.0*i*(nKnownPositions-1))/number_of_positions for i in range(number_of_positions)]

# interpolate locations
# create an interpolation object
Expand Down Expand Up @@ -301,7 +301,7 @@ def main():
GX.Tour(playlist),
)

print etree.tostring(fld, pretty_print=True)
print(etree.tostring(fld, pretty_print=True).decode())


if __name__=='__main__':
Expand Down
6 changes: 3 additions & 3 deletions src/examples/Tours/working_files/tour_from_linestring.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@
tour_doc[gxns+"Tour"].Playlist.append(flyto)

assert Schema('kml22gx.xsd').validate(tour_doc)
print etree.tostring(tour_doc, pretty_print=True)
print(etree.tostring(tour_doc, pretty_print=True).decode())

# output a KML file (named based on the Python script)
outfile = file(__file__.rstrip('.py')+'.kml','w')
outfile.write(etree.tostring(tour_doc, pretty_print=True))
with open(__file__.rstrip('.py')+'.kml','wb') as outfile:
outfile.write(etree.tostring(tour_doc, pretty_print=True))
333 changes: 333 additions & 0 deletions src/examples/data_conversion/eqs7day-M2.5.txt

Large diffs are not rendered by default.

13 changes: 6 additions & 7 deletions src/examples/data_conversion/example_csv_to_kml.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@
'''
import csv
import urllib2
from datetime import datetime
from lxml import etree
from pykml.factory import KML_ElementMaker as KML

def makeExtendedDataElements(datadict):
'''Converts a dictionary to ExtendedData/Data elements'''
edata = KML.ExtendedData()
for key, value in datadict.iteritems():
for key, value in datadict.items():
edata.append(KML.Data(KML.value(value), name=key + "_"))
return edata

Expand Down Expand Up @@ -49,7 +48,7 @@ def makeExtendedDataElements(datadict):
KML.Style(
KML.IconStyle(
KML.color(color),
KML.scale(threshold/2),
KML.scale(threshold/2.),
KML.Icon(
KML.href("http://maps.google.com/mapfiles/kml/shapes/earthquake.png"),
),
Expand All @@ -63,9 +62,9 @@ def makeExtendedDataElements(datadict):
doc.append(KML.Folder())

# read in a csv file, and create a placemark for each record
url="http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M2.5.txt"
fileobject = urllib2.urlopen(url)
for row in csv.DictReader(fileobject):
#url="http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M2.5.txt"
with open('eqs7day-M2.5.txt', 'r') as fd:
for row in csv.DictReader(fd):
timestamp = datetime.strptime(row["Datetime"], "%A, %B %d, %Y %H:%M:%S %Z")
pm = KML.Placemark(
KML.name("Magnitude={0}".format(row['Magnitude'])),
Expand All @@ -89,4 +88,4 @@ def makeExtendedDataElements(datadict):
schema_gx = Schema("kml22gx.xsd")
schema_gx.assertValid(doc)

print etree.tostring(doc, pretty_print=True)
print(etree.tostring(doc, pretty_print=True).decode())
11 changes: 6 additions & 5 deletions src/examples/misc/base_jump/virtual_base_jump.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/python
from __future__ import division

# example virtual base jump
import math
Expand Down Expand Up @@ -67,10 +68,10 @@ def drange(start, stop, step):
tstep = 0.1
for t in drange(0,15,tstep):
pm = kml.Placemark(
kml.name(str(t)),
kml.name("{name:.1f}".format(name=t)),
kml.Point(
kml.altitudeMode("absolute"),
kml.coordinates("{lon},{lat},{alt}".format(
kml.coordinates("{lon:.8f},{lat:.8f},{alt:.8f}".format(
lon=loc0['longitude'] + vx*t,
lat=loc0['latitude'] + vy*t,
alt=loc0['altitude'] + vz*t + 0.5*g*t**2,
Expand All @@ -96,8 +97,8 @@ def drange(start, stop, step):


assert Schema('kml22gx.xsd').validate(tour_doc)
print etree.tostring(tour_doc, pretty_print=True)
print(etree.tostring(tour_doc, pretty_print=True).decode())

# output a KML file (named based on the Python script)
outfile = file(__file__.rstrip('.py')+'.kml','w')
outfile.write(etree.tostring(tour_doc, pretty_print=True))
with open(__file__.rstrip('.py')+'.kml','wb') as outfile:
outfile.write(etree.tostring(tour_doc, pretty_print=True))
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,4 @@
),
),
)
print etree.tostring(etree.ElementTree(doc),pretty_print=True)

print(etree.tostring(etree.ElementTree(doc),pretty_print=True).decode())
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@
)
)

print etree.tostring(etree.ElementTree(kmlobj),pretty_print=True)
print(etree.tostring(etree.ElementTree(kmlobj),pretty_print=True).decode())
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@
)
)

print etree.tostring(etree.ElementTree(kmlobj),pretty_print=True)
print(etree.tostring(etree.ElementTree(kmlobj),pretty_print=True).decode())
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,4 @@
)
)

print etree.tostring(etree.ElementTree(kmlobj),pretty_print=True)
print(etree.tostring(etree.ElementTree(kmlobj),pretty_print=True).decode())
2 changes: 1 addition & 1 deletion src/examples/misc/hello_world/hello_world_5_globe_scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@
),
)
)
print etree.tostring(etree.ElementTree(kmlobj),pretty_print=True)
print(etree.tostring(etree.ElementTree(kmlobj),pretty_print=True).decode())
7 changes: 4 additions & 3 deletions src/examples/misc/pyephem/pyephem_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Example usage:
python pyephem_example.py > test.kml
'''
from __future__ import division

from datetime import datetime, timedelta
from math import pi, degrees, radians
Expand Down Expand Up @@ -99,7 +100,7 @@ def calculate_geographic_offset(azimuth_angle,altitude_angle, distance):
KML.Point(
KML.extrude(True),
KML.altitudeMode('relativeToGround'),
KML.coordinates("{0},{1},{2}".format(longitude,latitude,height)),
KML.coordinates("{0:.8f},{1:.8f},{2:.8f}".format(longitude,latitude,height)),
),
)
doc.Document.append(pm_observer)
Expand Down Expand Up @@ -133,7 +134,7 @@ def calculate_geographic_offset(azimuth_angle,altitude_angle, distance):
),
KML.Point(
KML.altitudeMode("relativeToGround"),
KML.coordinates("{lon},{lat},{alt}".format(
KML.coordinates("{lon:.8f},{lat:.8f},{alt:.8f}".format(
lon = longitude + degrees(delta_lon_rad),
lat = latitude + degrees(delta_lat_rad),
alt = height + delta_alt,
Expand Down Expand Up @@ -185,6 +186,6 @@ def calculate_geographic_offset(azimuth_angle,altitude_angle, distance):
)
)

print etree.tostring(doc, pretty_print=True)
print(etree.tostring(doc, pretty_print=True).decode())


51 changes: 30 additions & 21 deletions src/pykml/factory.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'''pyKML Factory Module
The pykml.factory module provides objects and functions that can be used to
create KML documents element-by-element.
The pykml.factory module provides objects and functions that can be used to
create KML documents element-by-element.
The factory module leverages `lxml's ElementMaker factory`_ objects to create
KML objects with the appropriate namespace prefixes.
Expand All @@ -11,6 +11,7 @@

from lxml import etree, objectify


nsmap={
None: "http://www.opengis.net/kml/2.2",
'atom': "http://www.w3.org/2005/Atom",
Expand Down Expand Up @@ -38,14 +39,14 @@

def get_factory_object_name(namespace):
"Returns the correct factory object for a given namespace"

factory_map = {
'http://www.opengis.net/kml/2.2': 'KML',
'http://www.w3.org/2005/Atom': 'ATOM',
'http://www.google.com/kml/ext/2.2': 'GX'
}
if namespace:
if factory_map.has_key(namespace):
if namespace in factory_map:
factory_object_name = factory_map[namespace]
else:
factory_object_name = None
Expand All @@ -56,23 +57,28 @@ def get_factory_object_name(namespace):

def write_python_script_for_kml_document(doc):
"Generates a python script that will construct a given KML document"
import StringIO
try: # Python2 support
import io
import StringIO
output = StringIO.StringIO()
except ImportError: # Python3 support
import io
output = io.StringIO()
from pykml.helpers import separate_namespace

output = StringIO.StringIO()

indent_size = 2

# add the etree package so that comments can be handled
output.write('from lxml import etree\n')

# add the namespace declaration section
output.write('from pykml.factory import KML_ElementMaker as KML\n')
output.write('from pykml.factory import ATOM_ElementMaker as ATOM\n')
output.write('from pykml.factory import GX_ElementMaker as GX\n')
output.write('\n')

level = 0
xml = StringIO.StringIO(etree.tostring(doc))
xml = io.BytesIO(etree.tostring(doc))
context = etree.iterparse(xml, events=("start", "end", "comment"))
output.write('doc = ')
last_action = None
Expand Down Expand Up @@ -153,20 +159,20 @@ def write_python_script_for_kml_document(doc):
elif action in ('end'):
level -= 1
if last_action == 'start':
output.pos -= 1
output.seek(output.tell()-1)
indent = ''
else:
indent = ' ' * level * indent_size
for att,val in elem.items():
output.write('{0} {1}="{2}",\n'.format(indent,att,val))
output.write('{0}),\n'.format(indent))
last_action = action

# remove the last comma
output.pos -= 2
output.seek(output.tell()-2)
output.truncate()
output.write('\n')

for entry in previous_list:
output.write('doc.addprevious({entry})\n'.format(
entry=entry
Expand All @@ -175,20 +181,23 @@ def write_python_script_for_kml_document(doc):
output.write('doc.addnext({entry})\n'.format(
entry=entry
))

# add python code to print out the KML document
output.write('print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n')
output.write('print(etree.tostring(etree.ElementTree(doc),pretty_print=True).decode())\n')

contents = output.getvalue()
output.close()
return contents

def kml2pykml():
"Parse a KML file and generates a pyKML script"
import urllib2
try: # Python2 support
import urllib2
except ImportError: # Python3 support
import urllib.request as urllib2
from pykml.parser import parse
from optparse import OptionParser

parser = OptionParser(
usage="usage: %prog FILENAME_or_URL",
version="%prog 0.1",
Expand All @@ -213,4 +222,4 @@ def kml2pykml():
pass #variable was not defined
else:
f.close
print write_python_script_for_kml_document(doc)
print(write_python_script_for_kml_document(doc))
Loading

0 comments on commit bb9a3f9

Please sign in to comment.