2013-03-03 72 views
2

OK,我的情况有点复杂,所以请让我来解释一下:程序加载Python模块/功能

  • 我的主要应用是在Objective-C /可可(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文件中)。

如何做到这一点?


旁注:我在Python的经验是最小 - 所以,裸跟我来! :-)

+0

注意:['finally:... return NO'](http://ideone.com/91kZPH)表示该函数总是返回“NO” – jfs 2013-03-03 15:51:34

回答

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