Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Port of gpxpy to Python 3 #4

Closed
wants to merge 5 commits into from

2 participants

@rob-smallshire

Hello, I've ported gpxpy to Python 3, whilst retaining compatibility with Python 2.7 (and possibly earlier).

rob-smallshire added some commits
@rob-smallshire rob-smallshire Updates .gitignore for PyCharm development
8916e42
@rob-smallshire rob-smallshire Port to Python 3, whilst retaining compatibility with Python 2, from …
…a single codebase. Also fixed a defect in gpx.reduce_points() revealed by Python 3 being stricter which object comparisons.
166afba
@tkrajina
Owner

Hi Robert,

I already responded you via email, but just for other users of gpxpy to know the status of this pull request:

Seems OK to me. I'll test it for a few days on a development version of www.trackprofiler.com. If everything is OK I'll merge your pull request (which, BTW, seems better than my try).

tk

@tkrajina
Owner

OK, I merged this to my branch rob-smallshire-python3, but (because of my previous merge of lxml compatibility branch) -- there are a test failures. When I fix them all it will be merged to master.

@tkrajina tkrajina closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 27, 2012
  1. @rob-smallshire
  2. @rob-smallshire

    Port to Python 3, whilst retaining compatibility with Python 2, from …

    rob-smallshire authored
    …a single codebase. Also fixed a defect in gpx.reduce_points() revealed by Python 3 being stricter which object comparisons.
Commits on Nov 28, 2012
  1. @rob-smallshire
Commits on Nov 29, 2012
  1. @rob-smallshire
  2. @rob-smallshire
This page is out of date. Refresh to see the latest.
View
40 .gitignore
@@ -1,8 +1,46 @@
MANIFEST
-*.pyc
*.swp
*.swo
tmp/
tmp_*.py
q.py
tags
+
+*.py[cod]
+
+# C extensions
+*.so
+
+# Packages
+*.egg
+*.egg-info
+dist
+build
+eggs
+parts
+bin
+var
+sdist
+develop-eggs
+.installed.cfg
+lib
+lib64
+
+# Installer logs
+pip-log.txt
+
+# Unit test / coverage reports
+.coverage
+.tox
+nosetests.xml
+
+# Translations
+*.mo
+
+# Mr Developer
+.mr.developer.cfg
+.project
+.pydevproject
+
+# PyCharm
+.idea
View
4 gpxpy/__init__.py
@@ -14,8 +14,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import gpx as mod_gpx
-import parser as mod_parser
+from . import gpx as mod_gpx
+from . import parser as mod_parser
def parse(xml_or_file):
""" Parse xml (string) or file object. This is just an wrapper for GPXParser.parse() function """
View
3  gpxpy/geo.py
@@ -15,7 +15,8 @@
# limitations under the License.
import math as mod_math
-import utils as mod_utils
+
+from . import utils as mod_utils
# Generic geo related function and class(es)
View
53 gpxpy/gpx.py
@@ -14,20 +14,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import pdb
+"""
+GPX related stuff
+"""
import logging as mod_logging
import math as mod_math
-import datetime as mod_datetime
import collections as mod_collections
-
-import utils as mod_utils
import copy as mod_copy
-import geo as mod_geo
-"""
-GPX related stuff
-"""
+from . import utils as mod_utils
+from . import geo as mod_geo
# GPX date format
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
@@ -61,11 +58,12 @@
PointData = mod_collections.namedtuple(
'PointData',
('point', 'distance_from_start', 'track_no', 'segment_no', 'point_no'))
+LinkData = mod_collections.namedtuple(
+ 'LinkData',
+ ('href', 'text', 'mime_type'))
class GPXException(Exception):
-
- def __init__(self, message):
- Exception.__init__(self, message)
+ pass
class GPXWaypoint(mod_geo.Location):
@@ -252,7 +250,7 @@ def __str__(self):
def to_xml(self, version=None):
content = ''
- if self.elevation != None:
+ if self.elevation is not None:
content += mod_utils.to_xml('ele', content=self.elevation)
if self.time:
content += mod_utils.to_xml('time', content=self.time.strftime(DATE_FORMAT))
@@ -297,7 +295,8 @@ class GPXTrackPoint(mod_geo.Location):
speed = None
def __init__(self, latitude, longitude, elevation=None, time=None, symbol=None, comment=None,
- horizontal_dilution=None, vertical_dilution=None, position_dilution=None, speed=None):
+ horizontal_dilution=None, vertical_dilution=None, position_dilution=None, speed=None,
+ links=None):
mod_geo.Location.__init__(self, latitude, longitude, elevation)
self.time = time
@@ -310,6 +309,8 @@ def __init__(self, latitude, longitude, elevation=None, time=None, symbol=None,
self.speed = speed
+ self.links = links if links is not None else []
+
def remove_time(self):
""" Will remove time metadata. """
self.time = None
@@ -336,6 +337,15 @@ def to_xml(self, version=None):
if self.speed:
content += mod_utils.to_xml('speed', content=self.speed)
+ for link in self.links:
+ link_content = ''
+ if link.text is not None:
+ link_content += mod_utils.to_xml('text', content=link.text)
+ if link.mime_type is not None:
+ link_content += mod_utils.to_xml('type', content=link.mime_type)
+ content += mod_utils.to_xml('link', attributes={'href':link.href},
+ content=link_content)
+
return mod_utils.to_xml('trkpt', {'lat': self.latitude, 'lon': self.longitude}, content=content)
def time_difference(self, track_point):
@@ -379,7 +389,7 @@ def __str__(self):
def __hash__(self):
return mod_utils.hash_object(self, 'latitude', 'longitude', 'elevation', 'time', 'symbol', 'comment',
- 'horizontal_dilution', 'vertical_dilution', 'position_dilution', 'speed')
+ 'horizontal_dilution', 'vertical_dilution', 'position_dilution', 'speed', 'links')
class GPXTrack:
name = None
@@ -1292,17 +1302,22 @@ def get_moving_data(self, stopped_speed_treshold=None):
return MovingData(moving_time, stopped_time, moving_distance, stopped_distance, max_speed)
- def reduce_points(self, max_points_no, min_distance=None):
+ def reduce_points(self, max_points_no=None, min_distance=None):
"""
Reduce this track to the desired number of points
max_points = The maximum number of points after the reduction
min_distance = The minimum distance between two points
"""
- if not min_distance:
- points_no = len(list(self.walk()))
- if not max_points_no or points_no <= max_points_no:
- return
+ if max_points_no is None and min_distance is None:
+ raise ValueError("Either max_point_no or min_distance must be supplied")
+
+ if max_points_no is not None and max_points_no < 2:
+ raise ValueError("max_points_no must be greater than or equal to 2")
+
+ points_no = len(list(self.walk()))
+ if max_points_no is not None and points_no <= max_points_no:
+ return
length = self.length_3d()
View
104 gpxpy/parser.py
@@ -14,48 +14,41 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import pdb
+from __future__ import print_function
import logging as mod_logging
import datetime as mod_datetime
-
import xml.dom.minidom as mod_minidom
-
-import gpx as mod_gpx
-import utils as mod_utils
import re as mod_re
+from . import gpx as mod_gpx
+from . import utils as mod_utils
+from .portability import has_key
+
+
def parse_time(string):
if not string:
return None
try:
return mod_datetime.datetime.strptime(string, mod_gpx.DATE_FORMAT)
- except Exception, e:
+ except Exception as e:
if mod_re.match('^.*\.\d+Z$', string):
string = mod_re.sub('\.\d+Z', 'Z', string)
try:
return mod_datetime.datetime.strptime(string, mod_gpx.DATE_FORMAT)
- except Exception, e:
+ except Exception as e:
mod_logging.error('Invalid timestemp %s' % string)
return None
+
+
class AbstractXMLParser:
""" Common methods used in GPXParser and KMLParser """
- gpx = None
- xml = None
+ def __init__(self, xml):
- valid = None
- error = None
-
- def init(self, xml_or_file):
- if hasattr(xml_or_file, 'read'):
- self.xml = xml_or_file.read()
- else:
- if isinstance(xml_or_file, unicode):
- self.xml = xml_or_file.encode('utf-8')
- else:
- self.xml = str(xml_or_file)
+ text = xml.read() if hasattr(xml, 'read') else xml
+ self.xml = mod_utils.make_str(text)
self.valid = False
self.error = None
@@ -81,18 +74,13 @@ def get_node_data(self, node):
class GPXParser(AbstractXMLParser):
- def __init__(self, xml_or_file=None):
- self.init(xml_or_file)
-
- self.gpx = mod_gpx.GPX()
-
def parse(self):
try:
dom = mod_minidom.parseString(self.xml)
self.__parse_dom(dom)
return self.gpx
- except Exception, e:
+ except Exception as e:
mod_logging.debug('Error in:\n%s\n-----------\n' % self.xml)
mod_logging.exception(e)
self.error = str(e)
@@ -144,19 +132,19 @@ def __parse_dom(self, dom):
self.valid = True
def _parse_bounds(self, node):
- if node.attributes.has_key('minlat'):
+ if has_key(node.attributes, 'minlat'):
self.gpx.min_latitude = mod_utils.to_number(node.attributes['minlat'].nodeValue)
- if node.attributes.has_key('maxlat'):
+ if has_key(node.attributes, 'maxlat'):
self.gpx.min_latitude = mod_utils.to_number(node.attributes['maxlat'].nodeValue)
- if node.attributes.has_key('minlon'):
+ if has_key(node.attributes, 'minlon'):
self.gpx.min_longitude = mod_utils.to_number(node.attributes['minlon'].nodeValue)
- if node.attributes.has_key('maxlon'):
+ if has_key(node.attributes, 'maxlon'):
self.gpx.min_longitude = mod_utils.to_number(node.attributes['maxlon'].nodeValue)
def _parse_waypoint(self, node):
- if not node.attributes.has_key('lat'):
+ if not has_key(node.attributes, 'lat'):
raise mod_gpx.GPXException('Waypoint without latitude')
- if not node.attributes.has_key('lon'):
+ if not has_key(node.attributes, 'lon'):
raise mod_gpx.GPXException('Waypoint without longitude')
lat = mod_utils.to_number(node.attributes['lat'].nodeValue)
@@ -220,9 +208,9 @@ def _parse_route(self, node):
return route
def _parse_route_point(self, node):
- if not node.attributes.has_key('lat'):
+ if not has_key(node.attributes, 'lat'):
raise mod_gpx.GPXException('Waypoint without latitude')
- if not node.attributes.has_key('lon'):
+ if not has_key(node.attributes, 'lon'):
raise mod_gpx.GPXException('Waypoint without longitude')
lat = mod_utils.to_number(node.attributes['lat'].nodeValue)
@@ -297,11 +285,11 @@ def __parse_track_segment(self, node):
def __parse_track_point(self, node):
latitude = None
- if node.attributes.has_key('lat'):
+ if has_key(node.attributes, 'lat'):
latitude = mod_utils.to_number(node.attributes['lat'].nodeValue)
longitude = None
- if node.attributes.has_key('lon'):
+ if has_key(node.attributes, 'lon'):
longitude = mod_utils.to_number(node.attributes['lon'].nodeValue)
time_node = mod_utils.find_first_node(node, 'time')
@@ -328,9 +316,26 @@ def __parse_track_point(self, node):
speed_node = mod_utils.find_first_node(node, 'speed')
speed = mod_utils.to_number(self.get_node_data(speed_node))
+ link_nodes = mod_utils.find_nodes(node, 'link')
+ links = [self.__parse_link(link) for link in link_nodes]
+
return mod_gpx.GPXTrackPoint(latitude=latitude, longitude=longitude, elevation=elevation, time=time,
symbol=symbol, comment=comment, horizontal_dilution=hdop, vertical_dilution=vdop,
- position_dilution=pdop, speed=speed)
+ position_dilution=pdop, speed=speed, links=links)
+
+
+ def __parse_link(self, node):
+ href = node.attribute['href'].nodeValue if has_key(node.attributes, 'href') else None
+
+ text_node = mod_utils.find_first_node(node, 'text')
+ text = self.get_node_data(text_node)
+
+ type_node = mod_utils.find_first_node(node, 'type')
+ mime_type = self.get_node_data(type_node)
+
+ return mod_gpx.LinkData(href=href, text=text, mime_type=mime_type)
+
+
class KMLParser(AbstractXMLParser):
"""
@@ -346,18 +351,13 @@ class KMLParser(AbstractXMLParser):
See http://code.google.com/apis/kml/documentation/kmlreference.html for more details.
"""
- gpx = None
-
- def __init__(self, xml_or_file=None):
- self.init(xml_or_file)
-
def parse(self):
try:
dom = mod_minidom.parseString(self.xml)
self.__parse_dom(dom)
return self.gpx
- except Exception, e:
+ except Exception as e:
mod_logging.debug('Error in:\n%s\n-----------\n' % self.xml)
mod_logging.exception(e)
self.error = str(e)
@@ -377,23 +377,23 @@ def __parse_dom(self, xml):
gpx_xml = file.read()
file.close()
- parser = mod_gpx.GPXParser(gpx_xml)
+ parser = GPXParser(gpx_xml)
gpx = parser.parse()
- print gpx.to_xml()
+ print(gpx.to_xml())
if parser.is_valid():
- print 'TRACKS:'
+ print('TRACKS:')
for track in gpx.tracks:
- print 'name%s, 2d:%s, 3d:%s' % (track.name, track.length_2d(), track.length_3d())
- print '\tTRACK SEGMENTS:'
+ print('name%s, 2d:%s, 3d:%s' % (track.name, track.length_2d(), track.length_3d()))
+ print('\tTRACK SEGMENTS:')
for track_segment in track.segments:
- print '\t2d:%s, 3d:%s' % (track_segment.length_2d(), track_segment.length_3d())
+ print('\t2d:%s, 3d:%s' % (track_segment.length_2d(), track_segment.length_3d()))
- print 'ROUTES:'
+ print('ROUTES:')
for route in gpx.routes:
- print route.name
+ print(route.name)
else:
- print 'error: %s' % parser.get_error()
+ print('error: %s' % parser.get_error())
View
51 gpxpy/portability.py
@@ -0,0 +1,51 @@
+"""Utilities for assisting with portability between Python 2 and Python 3.
+"""
+
+try:
+ # Python 2
+ #noinspection PyCompatibility
+ base = basestring
+ def is_string(s):
+ return isinstance(s, base)
+except NameError:
+ # Python 3
+ def is_string(s):
+ return isinstance(s, str)
+
+try:
+ # Python 2
+ #noinspection PyCompatibility
+ unicode()
+
+ def has_unicode_type():
+ return True
+
+except NameError:
+ # Python 3
+ def has_unicode_type():
+ return False
+
+
+try:
+ # Python 2
+ trial_dict = dict()
+ trial_dict.has_key('foo')
+ def has_key(d, key):
+ return d.has_key(key)
+except AttributeError:
+ # Python 3
+ def has_key(d, key):
+ return key in d
+finally:
+ del trial_dict
+
+
+try:
+ # Python 2.x and Python 3.2+
+ is_callable = callable
+except NameError:
+ # Python 3.0 and Python 3.1
+ from collections import Callable
+
+ def is_callable(x):
+ return isinstance(x, Callable)
View
22 gpxpy/utils.py
@@ -16,6 +16,7 @@
import logging
import xml.sax.saxutils as mod_saxutils
+from gpxpy.portability import has_unicode_type
def to_xml(tag, attributes={}, content=None, default=None, escape=False):
result = '\n<%s' % tag
@@ -38,8 +39,7 @@ def to_xml(tag, attributes={}, content=None, default=None, escape=False):
result += ''
- if isinstance(result, unicode):
- result = result.encode('utf-8')
+ result = make_str(result)
return result
@@ -64,6 +64,15 @@ def find_first_node(node, child_node_name):
return child_node
return None
+def find_nodes(node, child_node_name):
+ if not node or not child_node_name:
+ return
+ child_nodes = node.childNodes
+ for child_node in child_nodes:
+ if child_node.nodeName == child_node_name:
+ yield child_node
+
+
# Hash utilities:
def __hash(obj):
@@ -72,7 +81,7 @@ def __hash(obj):
if obj == None:
return result
elif isinstance(obj, dict):
- raise Error('__hash_single_object for dict not yet implemented')
+ raise RuntimeError('__hash_single_object for dict not yet implemented')
elif isinstance(obj, list) or isinstance(obj, tuple):
return hash_list_or_tuple(obj)
@@ -95,3 +104,10 @@ def hash_object(obj, *attributes):
return result
+def make_str(s):
+ """Convert a str or unicode object into a str type.
+ """
+ if has_unicode_type():
+ if isinstance(s, unicode):
+ return s.encode("utf-8")
+ return str(s)
View
7 setup.py
@@ -26,6 +26,11 @@
url = 'http://www.trackprofiler.com/gpxpy/index.html',
packages = [
'gpxpy',
- ],
+ ],
+ classifiers = [
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 2",
+ "Programming Language :: Python :: 3",
+ ],
)
View
133 test.py
@@ -14,6 +14,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+from __future__ import print_function
+
import pdb
import unittest as mod_unittest
@@ -22,12 +24,17 @@
import datetime as mod_datetime
import random as mod_random
import math as mod_math
+import io as mod_io
+import sys as mod_sys
import gpxpy as mod_gpxpy
import gpxpy.gpx as mod_gpx
import gpxpy.parser as mod_parser
import gpxpy.geo as mod_geo
+from gpxpy.portability import is_callable
+from gpxpy.utils import make_str
+
def equals(object1, object2, ignore=None):
""" Testing purposes only """
@@ -35,17 +42,17 @@ def equals(object1, object2, ignore=None):
return True
if not object1 or not object2:
- print 'Not obj2'
+ print('Not obj2')
return False
if not object1.__class__ == object2.__class__:
- print 'Not obj1'
+ print('Not obj1')
return False
attributes = []
for attr in dir(object1):
if not ignore or not attr in ignore:
- if not callable(getattr(object1, attr)) and not attr.startswith('_'):
+ if not is_callable(getattr(object1, attr)) and not attr.startswith('_'):
if not attr in attributes:
attributes.append(attr)
@@ -59,11 +66,11 @@ def equals(object1, object2, ignore=None):
if not attr1 and not attr2:
return True
if not attr1 or not attr2:
- print 'Object differs in attribute %s (%s - %s)' % (attr, attr1, attr2)
+ print('Object differs in attribute %s (%s - %s)' % (attr, attr1, attr2))
return False
if not equals(attr1, attr2):
- print 'Object differs in attribute %s (%s - %s)' % (attr, attr1, attr2)
+ print('Object differs in attribute %s (%s - %s)' % (attr, attr1, attr2))
return None
return True
@@ -72,14 +79,17 @@ def equals(object1, object2, ignore=None):
class Tests(mod_unittest.TestCase):
- def __parse(self, file):
- f = open('test_files/%s' % file)
+ def __parse(self, file, encoding=None):
+ if encoding is None:
+ encoding = mod_sys.getdefaultencoding()
+
+ f = mod_io.open('test_files/%s' % file, 'r', encoding=encoding)
parser = mod_parser.GPXParser(f)
gpx = parser.parse()
f.close()
if not gpx:
- print 'Parser error: %s' % parser.get_error()
+ print('Parser error: %s' % parser.get_error())
return gpx
@@ -90,7 +100,7 @@ def __reparse(self, gpx):
gpx = parser.parse()
if not gpx:
- print 'Parser error while reparsing: %s' % parser.get_error()
+ print('Parser error while reparsing: %s' % parser.get_error())
return gpx
@@ -102,8 +112,8 @@ def test_simple_parse_function_invalid_xml(self):
try:
mod_gpxpy.parse('<gpx></gpx')
self.fail()
- except mod_gpx.GPXException, e:
- self.assertTrue('unclosed token: line 1, column 5' in e.message)
+ except mod_gpx.GPXException as e:
+ self.assertTrue('unclosed token: line 1, column 5' in str(e))
def test_waypoints_equality_after_reparse(self):
gpx = self.__parse('cerknicko-jezero.gpx')
@@ -157,11 +167,11 @@ def test_has_times(self):
self.assertTrue(gpx.tracks[3].has_times())
def test_unicode(self):
- gpx = self.__parse('unicode.gpx')
+ gpx = self.__parse('unicode.gpx', encoding='utf8')
name = gpx.waypoints[0].name
- self.assertTrue(name.encode('utf-8') == 'šđčćž')
+ self.assertTrue(make_str(name) == 'šđčćž')
def test_nearest_location_1(self):
gpx = self.__parse('korita-zbevnica.gpx')
@@ -213,11 +223,11 @@ def test_reduce_gpx_file(self):
parser.parse()
time_reduced = mod_time.time() - started
- print time_original
- print points_original
+ print(time_original)
+ print(points_original)
- print time_reduced
- print points_reduced
+ print(time_reduced)
+ print(points_reduced)
self.assertTrue(time_reduced < time_original)
self.assertTrue(points_reduced < points_original)
@@ -240,11 +250,11 @@ def test_clone_and_smooth(self):
cloned_gpx.smooth(vertical=True, horizontal=True)
cloned_gpx.smooth(vertical=True, horizontal=False)
- print '2d:', gpx.length_2d()
- print '2d cloned and smoothed:', cloned_gpx.length_2d()
+ print('2d:', gpx.length_2d())
+ print('2d cloned and smoothed:', cloned_gpx.length_2d())
- print '3d:', gpx.length_3d()
- print '3d cloned and smoothed:', cloned_gpx.length_3d()
+ print('3d:', gpx.length_3d())
+ print('3d cloned and smoothed:', cloned_gpx.length_3d())
self.assertTrue(gpx.length_3d() == original_3d)
self.assertTrue(gpx.length_2d() == original_2d)
@@ -259,11 +269,11 @@ def test_reduce_by_min_distance(self):
for point, track_no, segment_no, point_no in gpx.walk():
if point_no > 0:
previous_point = gpx.tracks[track_no].segments[segment_no].points[point_no - 1]
- print point.distance_3d(previous_point)
+ print(point.distance_3d(previous_point))
if point.distance_3d(previous_point) < min_distance_before_reduce:
min_distance_before_reduce = point.distance_3d(previous_point)
- gpx.reduce_points(100000, min_distance=10)
+ gpx.reduce_points(min_distance=10)
min_distance_after_reduce = 1000000
for point, track_no, segment_no, point_no in gpx.walk():
@@ -283,14 +293,14 @@ def test_moving_stopped_times(self):
gpx = parser.parse()
f.close()
- print gpx.get_track_points_no()
+ print(gpx.get_track_points_no())
#gpx.reduce_points(1000, min_distance=5)
- print gpx.get_track_points_no()
+ print(gpx.get_track_points_no())
length = gpx.length_3d()
- print 'Distance: %s' % length
+ print('Distance: %s' % length)
gpx.reduce_points(2000, min_distance=10)
@@ -298,18 +308,18 @@ def test_moving_stopped_times(self):
gpx.smooth(vertical=True, horizontal=False)
moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data(stopped_speed_treshold=0.1)
- print '-----'
- print 'Length: %s' % length
- print 'Moving time: %s (%smin)' % (moving_time, moving_time / 60.)
- print 'Stopped time: %s (%smin)' % (stopped_time, stopped_time / 60.)
- print 'Moving distance: %s' % moving_distance
- print 'Stopped distance: %s' % stopped_distance
- print 'Max speed: %sm/s' % max_speed
- print '-----'
+ print('-----')
+ print('Length: %s' % length)
+ print('Moving time: %s (%smin)' % (moving_time, moving_time / 60.))
+ print('Stopped time: %s (%smin)' % (stopped_time, stopped_time / 60.))
+ print('Moving distance: %s' % moving_distance)
+ print('Stopped distance: %s' % stopped_distance)
+ print('Max speed: %sm/s' % max_speed)
+ print('-----')
# TODO: More tests and checks
self.assertTrue(moving_distance < length)
- print 'Dakle:', moving_distance, length
+ print('Dakle:', moving_distance, length)
self.assertTrue(moving_distance > 0.75 * length)
self.assertTrue(stopped_distance < 0.1 * length)
@@ -342,7 +352,7 @@ def test_split(self):
after = len(track.segments)
self.assertTrue(before + 1 == after)
- print 'Points in first (splitted) part:', len(track.segments[0].points)
+ print('Points in first (splitted) part:', len(track.segments[0].points))
# From 0 to 10th point == 11 points:
self.assertTrue(len(track.segments[0].points) == 11)
@@ -386,8 +396,8 @@ def test_remove_point_from_segment(self):
original_segment = segment.clone()
segment.remove_point(3)
- print segment.points[0]
- print original_segment.points[0]
+ print(segment.points[0])
+ print(original_segment.points[0])
self.assertTrue(equals(segment.points[0], original_segment.points[0]))
self.assertTrue(equals(segment.points[1], original_segment.points[1]))
self.assertTrue(equals(segment.points[2], original_segment.points[2]))
@@ -398,7 +408,7 @@ def test_remove_point_from_segment(self):
def test_distance(self):
distance = mod_geo.distance(48.56806,21.43467, None, 48.599214,21.430878, None)
- print distance
+ print(distance)
self.assertTrue(distance > 3450 and distance < 3500)
def test_horizontal_smooth_remove_extreemes(self):
@@ -412,8 +422,8 @@ def test_horizontal_smooth_remove_extreemes(self):
gpx.smooth(vertical=False, horizontal=True, remove_extreemes=True)
points_after = gpx.get_track_points_no()
- print points_before
- print points_after
+ print(points_before)
+ print(points_after)
self.assertTrue(points_before - 2 == points_after)
@@ -428,8 +438,8 @@ def test_vertical_smooth_remove_extreemes(self):
gpx.smooth(vertical=True, horizontal=False, remove_extreemes=True)
points_after = gpx.get_track_points_no()
- print points_before
- print points_after
+ print(points_before)
+ print(points_after)
self.assertTrue(points_before - 1 == points_after)
@@ -445,8 +455,8 @@ def test_horizontal_and_vertical_smooth_remove_extreemes(self):
gpx.smooth(vertical=True, horizontal=True, remove_extreemes=True)
points_after = gpx.get_track_points_no()
- print points_before
- print points_after
+ print(points_before)
+ print(points_after)
self.assertTrue(points_before - 3 == points_after)
@@ -505,7 +515,7 @@ def test_positions_on_track_2(self):
result = gpx.get_nearest_locations(location_to_find_on_track)
- print 'Found', result
+ print('Found', result)
self.assertTrue(len(result) == 2)
@@ -515,15 +525,15 @@ def test_hash_location(self):
self.assertTrue(hash(location_1) == hash(location_2))
- location_2.elevation *= 2
- location_2.latitude *= 2
- location_2.longitude *= 2
+ location_2.elevation *= 2.0
+ location_2.latitude *= 2.0
+ location_2.longitude *= 2.0
self.assertTrue(hash(location_1) != hash(location_2))
- location_2.elevation /= 2
- location_2.latitude /= 2
- location_2.longitude /= 2
+ location_2.elevation /= 2.0
+ location_2.latitude /= 2.0
+ location_2.longitude /= 2.0
self.assertTrue(hash(location_1) == hash(location_2))
@@ -533,15 +543,15 @@ def test_hash_gpx_track_point(self):
self.assertTrue(hash(point_1) == hash(point_2))
- point_2.elevation *= 2
- point_2.latitude *= 2
- point_2.longitude *= 2
+ point_2.elevation *= 2.0
+ point_2.latitude *= 2.0
+ point_2.longitude *= 2.0
self.assertTrue(hash(point_1) != hash(point_2))
- point_2.elevation /= 2
- point_2.latitude /= 2
- point_2.longitude /= 2
+ point_2.elevation /= 2.0
+ point_2.latitude /= 2.0
+ point_2.longitude /= 2.0
self.assertTrue(hash(point_1) == hash(point_2))
@@ -700,8 +710,8 @@ def test_get_bounds_and_refresh_bounds(self):
bounds = gpx.get_bounds()
- print latitudes
- print longitudes
+ print(latitudes)
+ print(longitudes)
self.assertEquals(bounds.min_latitude, min(latitudes))
self.assertEquals(bounds.max_latitude, max(latitudes))
@@ -809,7 +819,7 @@ def test_track_points_data(self):
self.assertTrue(gpx.length_2d() != gpx.length_3d())
def test_walk_route_points(self):
- gpx = mod_gpxpy.parse(file('test_files/route.gpx'))
+ gpx = mod_gpxpy.parse(open('test_files/route.gpx'))
for point in gpx.routes[0].walk(only_points=True):
self.assertTrue(point)
@@ -938,4 +948,3 @@ def test_angle_loc(self):
if __name__ == '__main__':
mod_unittest.main()
-als
Something went wrong with that request. Please try again.