You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python插件加载时设置模块的__name__变量?

如何在自定义插件加载器中设置模块的__name__属性

要实现你需要的判断逻辑,只需在执行模块代码前手动给创建的模块对象设置__name__属性。修改你的load_plugin函数如下:

NAME_PY='myplugin.py'
def load_plugin(self, dirname):
    filename = os.path.join(dirname, NAME_PY)
    module_name = filename[:-3]
    file_path = os.path.join(self.plugin_dir, filename)
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    # 在这里设置__name__属性
    module.__name__ = 'plugin'
    spec.loader.exec_module(module)

逻辑说明

  • 提前给模块对象赋值__name__ = 'plugin',当exec_module执行插件代码时,插件全局作用域里的__name__就会是这个值,触发if __name__ == 'plugin'的分支。
  • 当插件脚本被直接运行时,Python会自动把__name__设为'__main__',所以插件里的if __name__ == '__main__'分支会正常生效。

插件代码验证

你的插件代码可以保持不变:

if __name__ == 'plugin':
    print("Loaded from a plugin")
if __name__ == '__main__':
    print("This is a plugin, it is not an standalone python file")
  • 通过加载器加载插件时,会输出Loaded from a plugin
  • 直接运行插件脚本时,会输出This is a plugin, it is not an standalone python file

内容的提问来源于stack exchange,提问作者user3696153

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 21:32:42