3

I need to invoke python plug-in in the QGIS startup. So that the python script will do some functions repeatedly in the periodic intervals until the QGIS software gets closed.

Is there any way to get this done in QGIS?

2

2 Answers 2

3
  1. You can add your python code to project macros: start, save or close methods.

  2. You can create plugin and execute your code when plugin initialised. See. https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html#run-python-code-when-qgis-starts

0

You can register/load and run a plugin like this:

import sys
sys.path = ["your/path/aboveMyPlugin"] + sys.path
import MyPlugin
plugin = MyPlugin.classFactory(iface)
plugin.initGui()
plugin.run()

MyPlugin is the name of the plugin folder, which acts as a python package, because of the file init.py in that folder. Also it contains the function classFactory, which must be executed, to let QGIS load the plugin.

If this plugin is not inside the plugin folder, you can still import it after extending the PYTHONPATH, using the sys modul, as shown by the first two lines. They are unnecessary, if thats not the case.

your/path/aboveMyPlugin should point to the directory containing your plugin.

Lastly, when your plugin is loaded, it's action method must be called, to start it. In the most cases (always?), it is the run() method of your plugin.

I tried to set this as an QGIS macro, which executes on project start and I ended up with this:

from qgis.utils import iface

import sys
oldpath = sys.path
sys.path = ["your/path/aboveMyPlugin"] + sys.path
import MyPlugin
plugin = None

def openProject():
    global plugin
    plugin = PegelOnline.classFactory(iface)
    plugin.initGui()
    plugin.run()


def saveProject():
    pass

def closeProject():
    global plugin
    plugin.unload()

So, now, as you open a qgis project including that macros, it will show the imported plugin gui. Closing that project, will unload the plugin as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.