在Python中导入PyQGIS模块时遇到问题
因为我之前的问题被关闭了,所以我想改进一下,让大家知道这个问题对很多用户可能有帮助。我找到了一种可以绕过系统环境设置的SHELL启动器,这种方法是“传统的”,可以把Python和QGIS结合起来(也就是使用PyQGIS)。原版的运行得很好(可以在这里找到:http://inasafe.linfiniti.com/html/id/developer-docs/platform_windows.html)。我一直在尝试修改它,让大家可以使用自己喜欢的IDE,而不是像原版那样只能用Windows命令提示符。因此,我做了一些修改,最终得到了这个命令启动器:
@echo off
SET OSGEO4W_ROOT=C:\QUANTU~1
call "%OSGEO4W_ROOT%"\bin\o4w_env.bat
call "%OSGEO4W_ROOT%"\apps\Python27\Lib\idlelib\idle.pyw # this is the IDE I wanna use, but You can freely point to whatever You'd like
@echo off
SET GDAL_DRIVER_PATH=%IDLE%\bin\gdalplugins\1.9
path %PATH%;%OSGEO4W_ROOT%\apps\qgis\bin
path %PATH%;%OSGEO4W_ROOT%\apps\grass\grass-6.4.2\lib
path %PATH%;"%OSGEO4W_ROOT%\apps\Python27\Scripts\"
set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\qgis\python;
set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\Python27\Lib\site-packages
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis
start "Quantum GIS Shell" /B "cmd.exe" %*
不过,当我运行它的时候,它会打开idle.pyw,但我无法导入模块,就好像系统变量没有正确设置一样,尽管通过检查sys.path看起来是设置好的。我在导入(比如说)“qgis.core”模块时遇到的错误是:
ImportError: DLL load failed: Impossibile trovare il modulo specificato # (impossible to import the specified module)
我的操作系统是Windows XP sp3,Python版本是2.7.3,QGIS是Lisboa v.1.8。我希望有人能帮我解决这个问题,这样可以帮助大家解决导入PyQGIS模块的常见问题。
2 个回答
-1
运行Qgis并打开Python控制台,输入以下内容
- import sys
- sys.path
现在复制这个路径,并在你的Python代码顶部加入这个sys路径。
现在运行那段代码。
1
最后我成功制作了个人的命令行启动器!诀窍在于研究一下 o4w_env.bat
文件,弄明白第二行的“call”到底是干嘛的。
所以我尝试了一下,成功了,步骤如下:
把
idle.pyw
(或者你想用的IDE)复制到Quantum GIS
的主文件夹里(在我这儿是C:/Quantum_GIS_Lisboa
)把启动器(见第3点)复制到 "\bin" 文件夹里,文件扩展名是
.bat
运行这个启动器(只需双击一下):
@echo off SET OSGEO4W_ROOT=C:\QUANTU~1 call "%OSGEO4W_ROOT%"\bin\o4w_env.bat @echo off SET GDAL_DRIVER_PATH=%IDLE%\bin\gdalplugins\1.9 path %PATH%;%OSGEO4W_ROOT%\apps\qgis\bin path %PATH%;%OSGEO4W_ROOT%\apps\grass\grass-6.4.2\lib path %PATH%;"%OSGEO4W_ROOT%\apps\Python27\Scripts\" set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\qgis\python; set PYTHONPATH=%PYTHONPATH%;%OSGEO4W_ROOT%\apps\Python27\Lib\site-packages set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis start "Quantum GIS Shell" /B "idle.pyw" %* # This is where you specify the IDE # you want to use, mine is "idle.pyw", but if You copy another one (as in point 1), # you should replace "idle.pyw" with "<YOUR_IDE>"
希望这能帮助到大家。
干杯!