Example #1
0
def start_app(gui=True, cleanup=True):
    """
    Will start a QgsApplication and call all initialization code like
    registering the providers and other infrastructure.
    It will not load any plugins.
    You can always get the reference to a running app by calling `QgsApplication.instance()`.
    The initialization will only happen once, so it is safe to call this method repeatedly.

    Parameters
    ----------
    cleanup: Do cleanup on exit. Defaults to true.

    Returns
    -------
    QgsApplication
    A QgsApplication singleton
    """

    global QGISAPP  # pylint: disable=global-variable-undefined

    try:
        QGISAPP
    except NameError:

        # In python3 we need to convert to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = [os.fsencode(arg) for arg in sys.argv]
        except AttributeError:
            argvb = ['']

        if platform.system() == 'Darwin':
            QgsApplication.addLibraryPath(
                os.path.expandvars('$QGIS_PREFIX_PATH/../Plugins'))
            QgsApplication.addLibraryPath(
                os.path.expandvars('$QGIS_PREFIX_PATH/../Plugins/qgis'))
            QgsApplication.addLibraryPath(
                os.path.expandvars('$QGIS_PREFIX_PATH/../MacOS'))

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, gui)

        QGISAPP.initQgis()
        # click.echo(QGISAPP.showSettings())
        Processing.initialize()

        def debug_log_message(message, tag, level):
            """ Print debug message on console """
            click.secho('{}({}): {}'.format(tag, level, message), fg='yellow')

        QgsApplication.instance().messageLog().messageReceived.connect(
            debug_log_message)

        if cleanup:

            @atexit.register
            def exitQgis():  # pylint: disable=unused-variable
                """ Exit Qgis Application """
                QGISAPP.exitQgis()

    return QGISAPP