无法在Python中导入gdal?

16 投票
2 回答
48850 浏览
提问于 2025-04-15 14:55

我在Ubuntu Jaunty上安装并运行了gdal,但是我无法运行gdal2tiles,因为出现了错误:

Traceback (most recent call last):
  File "/usr/local/bin/gdal2tiles.py", line 42, in <module>
    import gdal
ImportError: No module named gdal

当我打开Python并输入import gdal时,也出现了同样的错误。

我已经设置了LD_LIBRARY_PATH(注意没有空格!)为/usr/local/lib,但似乎没有任何变化。

看起来Python找不到gdal。有人能帮忙吗?

谢谢!

2 个回答

5

我也遇到了同样的问题。不过我发现可能是因为包的名字和“gdal”不一样。

我在我的anaconda环境里用命令“conda install -c conda-forge gdal”安装了gdal。

然后我试着用Python脚本导入gdal,像是“import gdal”或者“from osgeo import gdal”,结果都不行。

我查看了这个包的地址,路径是“…/anaconda3/envs/(环境名称)/lib/python3.7/site-packages”,然后我复制了原始包的目录,把“GDAL-3.4.1-py3.7-linux-x86_64.egg-info”这个名字改成了“gdal”。更改包名

然后我发现这样就可以用了。我成功地用“import gdal”导入了gdal。

15

这似乎是一个“Python路径”的问题。Python会在一个特定的路径中查找库文件。你可以试试下面的命令:

import sys
sys.path

如果包含gdal.py和相关文件的目录不在这个列表中,Python就找不到它。这是“诊断”部分。要解决这个问题,你有几个选择……这些选择都基于了解Python是如何构建这个路径的规则。

  • 可以修改PYTHONPATH环境变量,把你想要的路径加进去。
  • 可以从包含你想要的库的目录启动Python。
  • 可以动态修改sys.path,比如用sys.path.append("/SomePath/To/MyStuff")。

我只在“官方”Python文档中看到过关于构建sys.path规则的描述,具体在教程的6.1.2节。
摘录:

modules are searched in the list of directories given by the variable sys.path
which is initialized from the directory containing the input script (or the 
current directory), PYTHONPATH and the installation- dependent default. This
allows Python programs that know what they’re doing to modify or replace the
module search path. Note that because the directory containing the script being
run is on the search path, it is important that the script not have the same name
as a standard module, or Python will attempt to load the script as a module when
that module is imported. This will generally be an error. See section
Standard Modules for more information.

撰写回答