How to execute lists of code? Or alternatives.

Fredrik Lundh effbot at telia.com
Tue May 9 17:39:45 CEST 2000


Remco Gerlich wrote:
> What I would love to have is to __import__ a module from a string.
> I don't think that's possible though.

# import module from string
# fredrik lundh, may 2000

import imp, sys

def do_import(name, source):
    module = imp.new_module(name)
    sys.modules[name] = module
    exec source in vars(module)
    return module

script = """
def hello():
    print 'hello you too'
"""

do_import("mymodule", script)

import mymodule
mymodule.hello()

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list