How to run pykml in python3

First, you need to install pykml for python3:

sudo pip3 install pykml

Now, if you try to read a kml file you will get the following message:

Python 3.6.3 (default, Oct  3 2017, 21:45:48) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pykml import parser
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/pykml/parser.py", line 8, in <module>
    import urllib2
ModuleNotFoundError: No module named 'urllib2'

To solve it, you need to fix urllib2 to work well in python3

If you try to install it with pip3 you will get:
                                                             
Collecting urllib2
  Could not find a version that satisfies the requirement urllib2 (from versions: )
No matching distribution found for urllib2

To solve it, you must edit /usr/local/lib/python3.6/dist-packages/pykml/parser.py and replace:

import urllib2

to

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

Now, you need update update the urllib2.urlopen() entries to just urlopen()

Save parser.py and try to import pykml again.
You can use the following example to get all coordinates from kml file:

from pykml import parser
from os import path

kml_file = path.join('file.kml')

with open(kml_file) as f:
  doc = parser.parse(f).getroot()

for e in doc.Document.Folder.Placemark:
  coor = e.Point.coordinates.text.split(',')
  print(coor)

Comments

Popular posts from this blog

Exception: Could not find a default OpenFlow controller in Mininet

How to fix Android when developer options are not available for this user

Webcam streaming throught VLC with YUY2 compatibility