Dynamic code use

Jason Morgan jwm-python at sentinelchicken.net
Thu Dec 26 20:51:31 EST 2002


Problem: I am writing a web application and have run into a situation
where I would like to dynamically decide on the code to run. I am trying
to use the recipe from the Cookbook (page 454) and have run into a
situation where I can't get my code to execute but I can get code
similar to the Cookbook example (very simple) to run.

Details:

# Cookbook import code (excluding additions to sys.modules)
def importCode(code, name):
	import imp
	module = imp.new_module(name)
	exec code in module.__dict__
	return module

Now, when I set code to something like:
code = """
def testFunc():
	print "Spam"
"""
and test it:
m = importCode(code,"test")
m.testFunc()

everything works fine. But when I use a file object or a string (either 
as a stand-alone string or a member of a list) containing my code, I get
an error like the following:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute 'generate'

Where 'generate' is the name of my function that creates some
dynamic HTML.

Would anyone have some insights into what I am doing wrong or, possibly,
another solution. My code dynamic code is located in many different
directories (this would not be easy to change) and often contains calls
to a MySQL database.

Thanks,

Jason




More information about the Python-list mailing list