[Tutor] imbedding python into another program?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Jun 2 02:06:47 CEST 2005



On Wed, 1 Jun 2005, Jeff Peery wrote:

> ok, thanks! that helps.  I have an application that reads a data file,
> crunches some numbers, and spits out some graphs.  In addition to this I
> would also like users to be able to write small python scripts to
> operate on the data that is available within the program. I suppose this
> could be accomplished by simply reading a text input and sending off the
> command to the command module and then returning the result to the
> user?? Is this feasible?


Hi Jeff,


Yes, this should be very feasible with the 'commands' module.


But if we're guaranteeing that we're going to work only with Python
programs, we can simplify this tremendously by just treating those
subprograms as modules.


Python allows us to dynamically load Python programs in as modules with
the '__import__' statement.  For example, let's say that we had two
programs in the current directory called 'foo.py' and 'bar.py'.


### foo.py ###
def sayHello():
    print "hellooo everybody, I'm so glad to see you."
######


### bar.py ###
def sayHello():
    print "como estas"
######


Once we have this, then we can do something like this:

### controller.py ###
import traceback
def main():
    while True:
        moduleName = raw_input(
            "Please enter a module name, or 'quit' to exit: ")
        if moduleName == 'quit':
            break
        try:
            dynamicModule = __import__(moduleName)
            dynamicModule.sayHello()
        except ImportError:
            traceback.print_exc()

if __name__ == '__main__':
    main()
######

The approach above can be seen as a "plugin"-style approach, where we
dynamically pull in modules and use a common interface to talk with them.


There's a lot of things we can take advantage of if we're in pure Python.
But if we're not, we're can still use some other kind of interprocess
communication mechanism, such as the 'commands' module or even 'xmlrpc' if
we want to be buzzword-compliant.  *grin*


Best of wishes!



More information about the Tutor mailing list