在startup.py脚本中安装后,如何自动重新加载插件?

编程语言 2026-07-09

在我的startup.py脚本中,我通过一个ZIP文件安装一个插件,插件已成功解压到QGIS用来查找插件的路径位置。

在同一个QGIS会话中,插件的按钮没有显示,根据 qgis.utils.active_plugins,看起来插件尚未激活。当我关闭当前的QGIS会话并重新打开一个新的会话时,插件现在已经处于激活状态并显示为一个按钮。

然而,让用户更少困惑的做法是插件直接一开始就显示出来,因为我会写日志消息说插件已安装。因此,某些用户可能会开始去找该插件,而实际插件尚不可用。
是否存在可以自动更新活动插件并重新加载插件的PyQGIS函数?

以下是我当前的startup.py脚本

from qgis.utils import iface
from PyQt5.QtCore import QTimer
from qgis.PyQt.QtCore import QSettings, QStandardPaths
from qgis.core import QgsMessageLog, Qgis
import zipfile
import os
import shutil

# Automatically detect the user's home directory
USER_HOME = os.path.expanduser("~")

# Folder containing the ZIP files
LOCAL_ZIP_FOLDER = os.path.join(
    USER_HOME,
    "Programs",
    "QGIS 3.40.8",
    "plugins",
    "Standaard actief"
)

# Plugins to install
PLUGIN_LIST = [
    'tools'#,

]

def plugin_dir():
    base = QStandardPaths.standardLocations(QStandardPaths.AppDataLocation)[0]
    return os.path.join(base, "profiles", "default", "python", "plugins")


def install_from_zip(plugin_name):
    zip_path = os.path.join(LOCAL_ZIP_FOLDER, plugin_name + ".zip")
    target_dir = os.path.join(plugin_dir(), plugin_name)

    if not os.path.isfile(zip_path):
        QgsMessageLog.logMessage(f"ZIP not found for {plugin_name}", "Startup", Qgis.Warning)
        return False

    if os.path.isdir(target_dir):
        shutil.rmtree(target_dir)

    try:
        with zipfile.ZipFile(zip_path, 'r') as z:
            z.extractall(plugin_dir())
        return True
    except Exception as e:
        QgsMessageLog.logMessage(f"Error extracting {plugin_name}: {e}", "Startup", Qgis.Critical)
        return False


def install():
    QgsMessageLog.logMessage("Local ZIP plugin installer started", "Startup", Qgis.Info)
    QgsMessageLog.logMessage(f"Installing into: {plugin_dir()}", "Startup", Qgis.Info)

    for plugin in PLUGIN_LIST:
        QgsMessageLog.logMessage(f"Installing {plugin} from ZIP", "Startup", Qgis.Info)

        if install_from_zip(plugin):
            QgsMessageLog.logMessage(f"{plugin} installed", "Startup", Qgis.Success)
        else:
            QgsMessageLog.logMessage(f"{plugin} failed to install", "Startup", Qgis.Warning)


def delayed_start():
    QTimer.singleShot(5000, install)

iface.initializationCompleted.connect(delayed_start)

解决方案

I'd take a look at the plugin_reload plugin which reloads a plugin during development to save having to restart QGis every time. It looks like this function contains the magic:

    \# Try to initially load the selected plugin if not loaded yet  
    if plugin not in qgis.utils.plugins:  
        qgis.utils.loadPlugin(plugin)  
        qgis.utils.startPlugin(plugin)  
        qgis.utils.updateAvailablePlugins()

Is probably the key bit,

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章