Skip to main content
 首页 » 编程设计

python之以编程方式加载 Python 模块/函数

2025年05月04日9pander-it

  • 我的主要应用程序是在 Objective-C/Cocoa (OS X) 中
  • 主要应用程序使用 Python“插件”进行“扩展”
  • 我们正在使用 Python 框架

这是我用作执行特定脚本的“桥梁”的代码:

from Foundation import * 
from AppKit import * 
 
import imp 
import sys 
 
class ppPluginBridge(NSObject): 
    @classmethod 
    def loadModuleAtPath_functionName_arguments_documents_(self, path, func, args,docs): 
 
        f = open(path) 
        try: 
             mod = imp.load_module('plugin', f, path, (".py", "r", imp.PY_SOURCE)) 
             realfunc = getattr(mod, func, None) 
             if realfunc is not None: 
                 realfunc(*tuple(args)) 
        except Exception as e: 
             docs.showConsoleError_('%s' % e) 
        finally: 
             f.close() 
             return NO 
 
        return YES 

所以这个函数在 path 中获取一个脚本并加载/执行它。

现在,我需要的是:使一些 python 类/函数/模块自动可用于最终脚本(在外部声明或 - 最好 - 在我的 ppPluginBridge.py 文件中声明)。

如何做到这一点?

请您参考如下方法:

首先,我会像这样加载一些东西:

>>> class Thingus: 
...     def __init__(self): 
...         module = __import__('string') 
...         setattr(self,module.__name__,module) 
...  
>>> thing = thingus() 
>>> thing.string 
<module 'string' from '/usr/lib/python2.7/string.pyc'> 
>>>  

请注意,这使用内置的导入功能进行导入,并且能够采用标准模块名称,如 this.that 而不是一些直接指向 Python 文件的路径。这更清洁。您只需要确保模块是正确的模块,并且在路径内。

至于指定要导入的内容,为什么不直接使用 ppPluginBridge.py 中的列表?你只需做类似的事情:

plugin_modules = [ 'plugins.loader', 'plugins.serializer' ] 

...或者你有什么。 Python 的表现力很强,因此将 Python 模块本身作为配置文件并没有错。当然,配置文件应该适本地分开,并在建立默认值后被版本控制系统忽略,以便各个安装可以更改它们。