Launching code on startup of QGIS

In this section we will describe how to launch specific Python code when QGIS is starting. It can configured it by using PYQGIS_STARTUP or by creating a Python script in home directory for QGIS. This folder is usually located in:

  • On Linux .local/share/QGIS/QGIS3/
  • On Windows: AppDataRoamingQGISQGIS3profilesdefaultpython
  • On macOS: Library/Application Support/QGIS/QGIS3/profiles/default

After you locate the correct directory, create a file called startup.py. This script will be run automatically on startup.

Note

As you can see above, path to this directory is different on every operation system. To locate it correctly, open Plugins ‣ Python console and type QStandardPaths.standardLocations(QStandardPaths.AppDataLocation) By such statement also presence of required modules can be checked.

# file example ~/.local/share/QGIS/QGIS3/startup.py

#
# adding custom path to Python plugins
#
import sys
sys.path.append("/home/user/python/plugins")

#
# activation of your Virtualenv
#
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
exec(
    compile(
        open(activate_this_file, "rb").read(),
        activate_this_file, 'exec'
    ),
    dict(__file__=activate_this_file)
)


#
# installation of missing packages
#
import pip
pip.main(['install', 'some_package'])

#
# checking presence of the packages
#
try:
    import fiona
    print("Everything is okay")
except ImportError as e:
    print("Fiona is not installed")

Thanks to that, our required modules (like fiona) and working environment are set up and ready to use.