External python file problem

Skip Montanaro skip at pobox.com
Wed Oct 31 10:23:51 EST 2001


    Thomas> i want a python program to load another .py file and execute a
    Thomas> function in this other file.  i compile the other file using the
    Thomas> compile function,but how to get the function i want from the
    Thomas> resulting code object ?

You're being much too hard on yourself.  Simply import the other module and
call the function.  Suppose your python program is in A.py and the other .py
file is B.py.  Simply execute

    import B
    B.func(...)

in A at the appropriate point.  If you don't know the name of the module and
function until runtime, use the __import__ builtin function:

    modname = raw_input("Enter module name: ")
    newmod = __import__(modname, globals(), {}, [])
    funcname = raw_input("Enter function name: ")
    newfunc = getattr(newmod, funcname)
    newfunc(...)

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list