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
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

  1. I like your blog, I read this blog please update more content on python, further check it once at python online training

    ReplyDelete

Post a Comment

Popular posts from this blog

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

from: can't read /var/mail/ in Python scripts

Fix "Set scan parameters failed: Input/output error" on Ubuntu 16.04