在QGIS中使用第三方Python模块

问题描述

我开发了使用第三方库的QGIS插件。 当前的情况是,该插件用户必须先在QGIS中安装一些Python库,然后才能使用我的插件。每次安装新的QGIS版本时,使用者都需要再次安装第三方库才能使用我的插件。 同样,在这种情况下,用户没有安装库的管理员权限。他们需要请公司服务台安装这些库。

是否有办法完全不用安装我使用的第三方库来打扰用户或公司服务台?

解决方法

在您的插件中创建一个require.txt文件,其中包含所有需要安装的软件包。然后在每次加载插件时执行它。 这是一个示例require.txt文件:

enter image description here

以下是您如何在插件中安装软件包的方法:

import pathlib
import sys
import os.path
def installer_func():
    plugin_dir = os.path.dirname(os.path.realpath(__file__))

    try:
        import pip
    except ImportError:
        exec(
            open(str(pathlib.Path(plugin_dir,'scripts','get_pip.py'))).read()
        )
        import pip
        # just in case the included version is old
        pip.main(['install','--upgrade','pip'])

    sys.path.append(plugin_dir)

    with open(os.path.join(plugin_dir,'requirements.txt'),"r") as requirements:
        for dep in requirements.readlines():
            dep = dep.strip().split("==")[0]
            try:
                __import__(dep)
            except ImportError as e:
                print("{} not available,installing".format(dep))
                pip.main(['install',dep])

在主文件中调用此函数。 您可以在插件说明中添加注释以管理员身份运行QGIS。