在Anaconda的Spyder中控制QGIS。
我将PAYTHONPATH
设置为C:\Program Files\QGIS Pisa\apps\qgis\bin
,但仍然在导入qgis.core
模块时出现此错误:
import qgis.core
ImportError: No module named qgis.core
如何导入模块?
j08lue提供的答案对我有用。但我们也可以在Anaconda虚拟环境中以特定的环境范围方式完成此操作。因此,请尝试以下步骤:
Create a conda environment using conda create -n conda-qgis
and then activate this new environment by using conda activate conda-qgis
.
Install QGIS through conda-forge in the current environment using conda install -c conda-forge qgis
.
Open QGIS by running qgis
.
Use the Python console in QGIS GUI, and run:
import sys
sys.path
and you might get system paths like below:
'C:/Anaconda3/envs/conda-qgis/Library/./python', 'C:/Users/Guohan/AppData/Roaming/QGIS/QGIS3\\profiles\\default/python', 'C:/Users/Guohan/AppData/Roaming/QGIS/QGIS3\\profiles\\default/python/plugins', 'C:/Anaconda3/envs/conda-qgis/Library/./python/plugins', 'C:\\Anaconda3\\envs\\conda-qgis\\Library\\python', 'C:\\Anaconda3\\envs\\conda-qgis\\Library\\python\\plugins', 'C:\\', 'C:\\Anaconda3\\envs\\conda-qgis\\python39.zip', 'C:\\Anaconda3\\envs\\conda-qgis\\DLLs', 'C:\\Anaconda3\\envs\\conda-qgis\\lib', 'C:\\Anaconda3\\envs\\conda-qgis\\Library\\bin', 'C:\\Anaconda3\\envs\\conda-qgis', 'C:\\Anaconda3\\envs\\conda-qgis\\lib\\site-packages', 'C:\\Anaconda3\\envs\\conda-qgis\\lib\\site-packages\\win32', 'C:\\Anaconda3\\envs\\conda-qgis\\lib\\site-packages\\win32\\lib', 'C:\\Anaconda3\\envs\\conda-qgis\\lib\\site-packages\\Pythonwin', 'C:/Users/Guohan/AppData/Roaming/QGIS/QGIS3\\profiles\\default/python'
Copy all the paths above and get back to the command prompt and run:
conda-develop PASTEHERE -n conda-qgis
This will create a conda.pth file at the site-package directory, which stores all the environment path variables specified for this conda-qgis environment.
Finally, you should be able to use import qgis
in an Anaconda environment.
QGIS中附带的Python包位于\path\to\QGIS\apps\Python27\Lib
。因此,您需要将其添加到PYTHONPATH
中,而不是...\qgis\bin
。
最好按脚本基础进行操作,而不是整个系统,像这样:
import sys
sys.path.append("C:\Program Files\QGIS Pisa\apps\Python27\Lib")
import qgis.core
请注意,QGIS Python软件包可能是为不同版本的Python构建的。因此,有些功能可能无法正常工作。
注意:QGIS Python插件安装在这里:~\.qgis2\python\plugins
,因此您可能需要sys.path.append
它。
这是关于2023年和QGIS 3的内容:即使我没有尝试重用C:\Program Files
下的安装,而是通过Anaconda(conda install -c conda-forge qgis
;在我的情况下,这是Miniconda3)安装了一个处理副本,但我无法让import qgis
正常工作。
起初,我只得到了一个ImportError
;这是在我的普通Powershell环境下。然后我打开了Anaconda Powershell提示符,但在那里也不起作用。执行conda init powershell
报告说没有要做的事情。我怀疑我PS环境中的其他调整可能会导致问题,所以我接着尝试了经典的(基于cmd.exe的)Anaconda提示符。
它起作用了。然后我将值sys.path
与其在Powershell下的值进行比较,发现对于某些原因,路径%CONDA_PREFIX%/Library/python
在后者中丢失。最终我通过在%CONDA_PREFIX%/Lib/site-packages
下创建一个.pth
文件并将缺失的路径粘贴到该文件中来解决这个问题。这样,每次激活环境时都会自动添加到sys.path
中,而我不必去修改%PYTHONPATH%
;这是不推荐的,因为Anaconda不使用它,当我第一次尝试使用它时,它破坏了我的环境。
P*A*ython
中有一个拼写错误吗?如果不是这个错误,请确保qgis库在你的路径上,你可以通过仔细检查`>>> import sys - Oliver W.