In the previous article titled "Displaying Selected Layer Count in QGIS with PyQGIS - MalaGIS", the author introduced a method to quickly view the number of selected layers using QGIS's Python API. However, if you need this functionality, you must open QGIS, then open the Python Console, locate the saved Python script file, and run it every single time. Although this process is simple, it can become tedious after repeated use. So, is there a way to automatically run a Python script when QGIS starts up? The author searched online and finally found a temporarily viable method to share today.

Software Information

The author uses QGIS version 3.44.2 on macOS. Many methods were found online, including those from DeepSeek, ChatGPT, and Gemini, but upon personal testing and download, they were basically ineffective. So, if you have other methods, please feel free to leave a comment for discussion.

Usage Method

Open the QGIS user directory. The location may vary on different operating systems.

On macOS, it is:

~/Library/Application Support/QGIS/QGIS3/profiles/default/

Continue navigating down to the processing/scripts directory and save the script file here. For example, the author wrote a test script:

from qgis.utils import iface

def my_startup_script():
    iface.messageBar().pushMessage("Hello", "QGIS2222 has started, and the script ran successfully!")

my_startup_script()

Save the file, then restart QGIS. You will see the following prompt:

Another Method

The author also found another method: after opening the user directory, navigate up to the ~/Library/Application Support/QGIS/QGIS3/ directory, save the script file here, and name it startup.py. Restart QGIS, and the script will also run automatically.

Afterword

The author believes that while this method works, it is still somewhat less than ideal. A better approach would be to package it as a plugin. The packaging method will be introduced later. If there are other methods, please feel free to leave a comment for discussion.