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

时间:2013-03-03 08:24:45

标签: python objective-c macos cocoa

  • 我的主要应用是Objective-C / Cocoa(OS X)
  • 主要应用程序是使用Python“plugins”
  • “扩展”的
  • 我们正在使用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文件中声明)。

怎么办呢?

1 个答案:

答案 0 :(得分:1)

首先,我会加载更像这样的东西:

>>> 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模块本身作为配置文件没有任何问题。当然,配置文件应该是正确分开的,并且在版本控制系统建立默认值后会被版本控制系统忽略,以便各个安装可以更改它们。

相关问题