Skip to content

Startup Scripts using Python

API Note: Any QGIS APIs referenced will link out to the Python API Docs.

Startup scripts a great way to tweak what happens to QGIS on startup. This startup scripts have access to the full QGIS API and Python so are able to do generally anything that is needed to customize an environment.

QGIS has three places it can use Python on start up.

They are:

  • --code command line option
  • startup.py in the root app data folder for QGIS
  • PYQGIS_STARTUP environment variable

Using --code

Exercise: Writing the startup script

Use the script editor and create a new file with the following code using QgsMessageBar.pushMessage to push the message on the message bar.

from qgis.utils import iface

iface.messageBar().pushMessage("FOSS4G", "FOSS4G for the win!")

Run the script and you can see the message. If we need it to stick there we can use:

from qgis.utils import iface

iface.messageBar().pushMessage("FOSS4G", "FOSS4G for the win!",duration=0)

We will save this script using the save button e.g C:\temp\workshop\code-startup.py

Exercise: Adding the --code to the shortcut

Take a copy of the QGIS shortcut and add the following:

 --code "C:\temp\workshop\code-startup.py"

The full shortcut should look like this:

Function Editor

Load QGIS using the new shortcut.

Function Editor

Using startup.py

The next example is using startup.py

startup.py is loaded from the app data folder for QGIS.

Exercise: Finding the startup.py

We can find the app data folder for QGIS using User Profiles -> Open Active Profile Folder

This will open the current profile folder for you at:

C:\Users\YOURUSER\AppData\Roaming\QGIS\QGIS3\profiles\default

However startup.py will live in C:\Users\YOURUSER\AppData\Roaming\QGIS\QGIS3 as it is used by all profiles.

Exercise: Editing the startup.py file

Create a empty text file there called startup.py

Function Editor

Open the script in the function editor and load that file:

Function Editor

Now enter the following:

iface.messageBar().pushMessage("FOSS4G", "Hello From Start Up", duration=0)

Save the file and load a new copy of QGIS. (Note: Not the one with the extra --code option from before)

Function Editor

PYQGIS_STARTUP

This one is a bit more advanced as it happens before any of the QGIS libraries are loaded and it's use case is limited. It included here to highlight it as a option but it's use case is limited.