Setting up PyQGIS3 with VSCode & Python3 on Windows

ModuleNotFoundError: No module named 'qgis'

This error got you down? Here’s how I solved it in my vscode and Python and QGIS environment on Windows.


This blog post by Gary is excellent for building a development environment for PyQGIS on Windows: Quick Guide to Getting Started with PyQGIS3 On Windows (Spatialgalaxy.net).

In this post we put a slight twist on it, just to be different, and to learn to use Visual Studio Code, on Windows, and without external setup scripts. There were multiple issues that held me back on it this but ultimately it was just my knowledge of vscode that needed an upgrade.

In a nutshell, for a minimal working example, you need four components: a QGIS install, a vscode workspace file, a .env file, and a Python script in the same folder.

QGIS install

In this case, I use a standard release installer from QGIS.org to get set up on Windows (not OSGeo4W). The install location is on a secondary drive, not the long file name with a couple of spaces – that is not a concern with this approach.

Note that the Python modules for both PyQGIS, PyQT5 are included in this install! More below on that.

D:\Program Files\QGIS 3.12\

vscode workspace

I’ve worked on various development projects with vscode before and never worried much about this workspace concept with them.

If you create a file by hand, it will then allow you to open the folder as a workspace. I suggest creating all the files below first, then opening it in vscode (File-> Open Folder).

If you do not have one of these JSON format files already, it will prompt you to create/save one. The one it created for me wasn’t very helpful as it had the wrong paths in it and it messed me up further.

Here is my workspace definition file, saved in:

c:\users\tyler\source\repos\diy-gis\workspace.code-workspace
{
	"folders": [
		{
			"name": "app",
			"path": "C:\\Users\\tyler\\source\\repos\\diy-gis"
		}
	]
}

All the file does is define the path for the rest of the project. This seems important when you go to launch the Python script,we didn’t worry about any other settings in this file when doing my testing. But it doesn’t mean it’s good enough for further uses especially build/deploy scenarios.

vscode .env file

The .env file is used to set environment variables before running a Python project in a vscode. It appears to require a workspace to be defined as well, see above.

Common system-wide/global Windows environment settings should work but I wanted this to all be self-contained in a single project workspace.

In the .env file, we simply put two lines, one for the PATH and one for the PYTHONPATH to point to our QGIS installation. Adjust for your version and path.

PATH=$PATH;"D:\Program Files\QGIS 3.18\bin\";"D:\Program Files\QGIS 3.18\apps\qgis\bin"
PYTHONPATH="D:\Program Files\QGIS 3.12\apps\qgis\python"

Basic Python app with QGIS module loaded

As we were early in this project let’s ensure that PyQT5 and QGIS modules would load into the Python project.

In the QGIS apps\qgis\python folder are the modules that Python will use, per the .env file above.

Some places will tell you to install PyQT5 with pip and that is not necessary if you have things set up this way. Plus you’ll know that your versions of QT and PyQGIS will be compatible if you use the same location for the modules.

This code uses both those modules and builds a very basic Hello World app. The file is app1.py in my workspace.

import sys
import qgis

from PyQt5.QtWidgets import QApplication, QWidget, QLabel

def window():
   app = QApplication(sys.argv)
   widget = QWidget()

   textLabel = QLabel(widget)
   textLabel.setText("Hello World!")
   textLabel.move(110,85)

   widget.setGeometry(50,50,320,200)
   widget.setWindowTitle("PyQt5 Example")
   widget.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

Next, with the app1.py open in vscode, I run the app script from the Run -> Run Without Debugging tool and see the application window pop up!

If things go wrong, check the terminal/console for any errors, here is my terminal output from vscode:

PS C:\Users\tyler\source\repos\diy-gis>  c:; cd 'c:\Users\tyler\source\repos\diy-gis'; & 'C:\python38\python.exe' 'c:\Users\tyler\.vscode\extensions\ms-python.python-2021.10.1365161279\pythonFiles\lib\python\debugpy\launcher' '54781' '--' 'c:\Users\tyler\source\repos\diy-gis\app1.py' 

If I comment out the PYTHONPATH from the .env file, I get my errors finding the PyQGIS module: qgis. Note that I do not get errors for PyQt because I also had them installed by pip in my main Python installation.

Traceback (most recent call last):
  File "c:\Users\tyler\source\repos\diy-gis\app1.py", line 2, in <module>
    import qgis
ModuleNotFoundError: No module named 'qgis'
PS C:\Users\tyler\source\repos\diy-gis>

Resources

The PyQGIS Programmer's Guide 3 - Extending QGIS 3 with Python 3 by Gary Sherman

Overview of our Geospatial Book Titles

It can be hard to know what book to buy when you are just starting to learn open source geospatial technology. This post outlines each GIS & geospatial book in our catalog to help give you the top takeaways to consider.

Geospatial & GIS book categories

Locate Press books cover a wide range of topics but they all fit into a few simple categories which we review, in-depth, after the following summaries.

QGIS book titles cover comprehensively learning the software, designing good maps with it, applying to the domain of hydrology, and writing custom applications with Python.

Specialized geospatial software titles cover web-based mapping, routing analysis, and general raster/vector data management.

General GIS titles covers a wide range of geospatial desktop technology as well as teaching the principles of GIS in a classroom-friendly way for younger students.

QGIS books

Introduction to QGIS - Open Source Geographic Information System by Scott Madry

Introduction to QGIS

Open Source Geographic Information Systems (GIS)

by Scott Madry Ph.D.

Scott’s book applies to QGIS 3.16 LTR edition, covering the latest stable version of QGIS.

This books introduces how QGIS works, with the user interface, handling different kinds of files, import and export.

Learn the processing toolbox, modeler, and the Python console in particular. Fundamental GIS topics such as raster/vector analysis, 3D map viewing, and map production in QGIS are covered.

QGIS for Hydrological Applications - Recipes for Catchment Hydrology and Water Management by Hans van der Kwast and Kurt Menke

QGIS for Hydrological Applications

Recipes for Catchment Hydrology and Water Management

by Hans van der Kwast and Kurt Menke

Hans and Kurt’s popular domain-focused text contains core knowledge for handling data in the hydrology field, including lab exercises and links to more teaching resources.

It includes map algebra, delineating streams, and land cover calculations for catchments. And QGIS basics: digitizing, importing tabular data, interpolating data into rasters, and georeferencing scanned maps.

Discover QGIS 3.x - A Workbook for Classroom or Independent Study by Kurt Menke

Discover QGIS 3.x – A Workbook for Classroom or Independent study

by Kurt Menke

This updated QGIS training workbook uses structured study of core geospatial concepts and GIS functions from the latest QGIS 3.x Long Term Release version.

New sections are included in this 2019 update covering advanced data visualization with layer effects, 3D maps, blending modes, and more.

A complete training course — exercises, questions, and solutions are provided.

QGIS Map Design - Second Edition by Anita Graser and Gretchen N. Peterson

QGIS Map Design – Second Edition

by Anita Graser & Gretchen N. Peterson

Have you ever wanted to improve your cartography output from QGIS 3? Learn step-by-step instructions to create compelling visuals and new workflows in this second edition.

Basic QGIS knowledge is presumed as the focus is on building maps with the newest and latest functionality of QGIS – including atlases, multitudinous color tools, map label generation, printable maps, and more.

The PyQGIS Programmer's Guide 3 - Extending QGIS 3 with Python 3 by Gary Sherman

The PyQGIS Programmer’s Guide – Extending QGIS 3 with Python 3

by Gary Sherman

Learn the QGIS 3 Python API for writing scripts and creating plugins.

A chapter is dedicated to helping you set up your development environment and to have a productive development workflow. Each chapter includes exercises for you to put your knowledge to work.

This is an update from the earlier QGIS 2 / Python 2 edition.

On the Way with GIS - Student and Teacher Edition by Toni Fisher

On the Way with QGIS – Student and Teacher Edition

by Toni Fisher

Written for teachers and students, those aged 10 to 15 years old continue learning GIS by building on the lessons and concepts from Fisher’s earlier work, Open the Door to GIS.

This edition introduces more advanced topics and encourages inquiry-based learning techniques and storytelling to inspire creativity, problem solving, and building confidence as they work through various scenarios.

Open the Door to GIS - Student and Teacher Edition by Toni Fisher

Open the Door to GIS – Student and Teacher Edition

By Toni Fisher

Introduce students (age 10 to 15 years) to analytical and graphical skill using open-source GIS technology.

Creative storytelling is used with QGIS to teach students skills for making treasure maps, creating a game, and more, alongside characters in the stories.

Creativity and reflection are encouraged as they grow throughout these weekly lessons covering a full semester.

Other categories

The above books cover all the current QGIS training books. In another post, we will introduce the specialized application books (pgRouting, Leaflet) and the more general GIS training books as well (Desktop GIS, GDAL).

%d bloggers like this: