Firstly, I see you have a standalone install of QGIS; my answer is based on an OSGeo4W install (it's been a while since I used the standalone installers) but I think the approach should be much the same.
If you just want to use a python shell, you can make a copy of your osgeo4w.bat file in the same location and rename it (like osgeo4w_pyqgis.bat) or whatever you like...
Open it in a text editor, find the line which calls o4w_env.bat, just replace o4w_env.bat
with python-qgis-ltr.bat
and save.
So mine (for 2.18) would look like this:
@echo off
rem Root OSGEO4W home dir to the same directory this script exists in
call "%~dp0\bin\python-qgis-ltr.bat"
rem List available o4w programs
rem but only if osgeo4w called without parameters
@echo on
@if [%1]==[] (echo run o-help for a list of available commands & cmd.exe /k) else (cmd /c "%*")
When you double click on this batch file it should open you up directly to a python prompt with environment variables correctly set. You can test this by typing from qgis.core import *
and hitting enter to make sure you don't get any errors.
Typing quit() or exit() once will take you back to an osgeo4w shell.
Another approach is to use a batch file like this:
@echo off
SET OSGEO4W_ROOT=C:\OSGeo4W64
SET QGISNAME=qgis-ltr
SET QGIS=%OSGEO4W_ROOT%\apps\%QGISNAME%
SET QGIS_PREFIX_PATH=%QGIS%
CALL %OSGEO4W_ROOT%\bin\o4w_env.bat
SET PATH=%PATH%;%QGIS%\bin
SET PYTHONPATH=%QGIS%\python;%PYTHONPATH%
cmd.exe
Again this is for an OsGeo4W install; for a standalone install, I think you would just have to change this line:
SET OSGEO4W_ROOT=C:\OSGeo4W64
Not 100% sure, but I think setting osgeo4w_root to C:\Program Files\QGIS 2.18 should work.
The advantage of this batch file is that you can change the last line to start an IDE such as PyCharm with environment variables correctly set for pyqgis development.
Try to use this .bat file to launch PyCharm:
@ECHO off
set OSGEO4W_ROOT=C:\OSGeo4W
call "%OSGEO4W_ROOT%\bin\o4w_env.bat"
call "%OSGEO4W_ROOT%\bin\qt5_env.bat"
call "%OSGEO4W_ROOT%\bin\py3_env.bat"
call "%OSGEO4W_ROOT%\apps\grass\grass78\etc\env.bat"
path %OSGEO4W_ROOT%\apps\qgis\bin;%PATH%
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis
set GDAL_FILENAME_IS_UTF8=YES
set VSI_CACHE=TRUE
set VSI_CACHE_SIZE=1000000
set QT_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\qgis\qtplugins;%OSGEO4W_ROOT%\apps\qt5\plugins
SET PYCHARM="C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.4\bin\pycharm64.exe"
set PYTHONPATH=%OSGEO4W_ROOT%\apps\qgis\python
set PYTHONHOME=%OSGEO4W_ROOT%\apps\Python39
set PYTHONPATH=%OSGEO4W_ROOT%\apps\Python39\lib\site-packages;%PYTHONPATH%
set QT_QPA_PLATFORM_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\Qt5\plugins\platforms
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis
start "PyCharm aware of QGIS" /B %PYCHARM% %*
Best Answer
You probably need to preliminarily import the layer before calling it.
If
pl
is a shapefile:If
pl
is a raster: