Python can't import gdal even though pip says it's installed - ubuntu hirsute & impish specific

Viewed 276

Update to clarify: The steps to install gdal for Python on ubuntu:focal appear to work for ubuntu:hirsute and ubuntu:impish, with pip reporting that gdal is installed. But trying to import it gives a ModuleNotFoundError only on hirsute and impish, not focal.

I've spent a while trying to figure out how to install gdal in a docker image based on ubuntu:hirsute. I get to where the install looks successful, and pip thinks gdal is installed. The following example runs correctly if I downgrade from ubuntu:hirsute to ubuntu:focal, but with hirsute or impish it gives:

 => ERROR [6/6] RUN python3 /src/test_gdal.py                                                                          0.3s
------
 > [6/6] RUN python3 /src/test_gdal.py:
#10 0.305 Traceback (most recent call last):
#10 0.305   File "/src/test_gdal.py", line 1, in <module>
#10 0.305     import gdal
#10 0.305 ModuleNotFoundError: No module named 'gdal'

Reproduce: Put these 2 files in a directory and run docker build . from that directory.

test_gdal.py:

import gdal

Dockerfile

FROM ubuntu:hirsute

SHELL ["/bin/bash", "-c"]

RUN apt-get update -y  && \
    apt-get install -y  python3.9 && \
    apt-get install -y pip

RUN apt-get update && \
    apt-get install -y gdal-bin && \
    apt-get install -y libgdal-dev

RUN pip install gdal

COPY . /src

RUN python3 /src/test_gdal.py
1 Answers

Since it saved me, I'm going to go ahead and add Robert Davy's comment as an answer:

https://gdal.org/api/python.html#usage shows that as of GDAL 3.1, gdal and such are now packages within osgeo, so you would import them not with

# Outdated    
import gdal

but with

from osgeo import gdal

Don't know whether it solved your issues, I'm on Windows -- the OS likely is unimportant, only the version of gdal installed? But since this can be an answer to the main idea of your question, will offer it up as an option for others who happen to come with the same issue who happen to be using older code with direct import gdal commands.

Related