1

Due to several reasons I sometimes want to use PyQGIS outside of QGIS, without using Python IDEs like PyCharm or Spyder.

Am trying to run Python from the OSGeo4W Shell on Windows but am constantly struggling to import PyQGIS

I found this and this, but the former requires using PyCharm and the second Spyder. There are some other questions on Stack Exchange but in most of them it is assumed that lines such as

import qgis.core 
import qgis.gui

are working, but that is precisely what is not working for me as am getting

>>> import qgis.core
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'qgis'

Anyone knows how to import PyQGIS outside QGIS without using IDEs like PyCharm or Spyder?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Juan Ossa
  • 594
  • 3
  • 13

1 Answers1

4

The following answer is for Windows:

In the installation folder of QGIS in the subfolder /bin you will find the python-qgis.bat file, which you can call with your pythonscript as parameter. I usually use a .bat file with the following command:
"C:\Program Files\QGIS 3.16\bin\python-qgis.bat" process1.py
where process1.py is my QGIS task in python

eurojam
  • 10,762
  • 1
  • 13
  • 27
  • Thanks @eurojam ... I understand this method will use the python interpreter provided by QGIS installation (so any packages you could need would have to be reinstalled from that python environment). What if you already have a bunch of Python scripts and packages installed in i.e. C:\Python38, prior to QGIS/OSGEO4W installation ... and now you want to call QGIS from your old scripts? Do you know how to use import and use PyQGIS from your own Python environment? – abu Jan 25 '22 at 08:28