2
  • My main application is in Objective-C/Cocoa (OS X)
  • The main application is "extended" using Python "plugins"
  • We're making use of the Python framework

This is the code I'm using as a "bridge" to execute a specific script:

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

So this function takes a script in path and loads/executes it.

Now, what I need is : make some python classes/functions/modules automatically available to the final script (either declared externally or - preferably - in my ppPluginBridge.py file).

How can that be done?

1
  • note: finally: ... return NO means that the function always returns NO Commented Mar 3, 2013 at 15:51

1 Answer 1

1

First, I'd do loading something more like this:

>>> 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'>
>>> 

Note that this uses the built-in import function to import and is able to take standard module names, like this.that rather than some direct path to a Python file. This is cleaner. You just need to make sure the modules are proper modules, and are within the path.

As for specifying what things you'd like to import, why not just use a list within ppPluginBridge.py? You'd just do something like:

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

...or what have you. Python is very expressive, so there's nothing wrong with making a Python module a configuration file in itself. Configuration files should, of course, be properly separate, and ignored by version control systems after their defaults are established so that individual installations can change them.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.