Search code examples
pythongdal

No module named _gdal


I am trying to run a Python script test.py to test the gdal library. The script contains the line:

from osgeo import gdal

At that line I get the traceback:

File "~/test.py", line 9, in <module>
    from osgeo import gdal
File "/usr/local/lib/python2.7/site-packages/GDAL-2.2.0/osgeo/__init__.py", line 21, in <module>
    gdal = swing_import_helper()
File "/usr/local/lib/python2.7/site-packages/GDAL-2.2.0/osgeo/__init__.py", line 13, in swig_import_helper
    import gdal
ImportError: No module named _gdal

I don't see any _gdal Python files or any scripts that define _gdal. Do I need to install another (prerequisite) library that defines _gdal? The GDAL package should include everything needed to install the library and run scripts that import gdal.


Solution

  • Along with the other answers here this can also happen if you build and install from sources then attempt to run the test command from the same folder that contains the osgeo python bindings, namely swig/python/.

    By default running python -c 'from osgeo import gdal; print(gdal.__version__)' from that location will fail.

    Since I only wanted to search the installation site-packages folder for the new module the solution was to run python in isolation mode so that the current directory was no longer included:

    python -I -c 'from osgeo import gdal; print(gdal.__version__)'