Execute external code and get return value
Peter Otten
__peter__ at web.de
Fri Sep 29 09:15:03 EDT 2006
Michele Petrazzo wrote:
> Following this link, here is my solution:
>
>
> code = """
> def funct2Call():
> return "It work!"
>
> object.method(funct2Call)
> """
>
> class Object(object):
> def method(self, value):
> self._callable = value
> def __call__(self):
> return self._callable()
>
> # populate the namespace
> namespace = {
> "object": Object()
> }
>
> # execute the code
> exec code in namespace
>
> namespace["object"]()
Just in case you didn't see it -- the following will work as well:
code = """
def funct2Call():
return "It work!"
"""
namespace = {}
exec code in namespace
namespace["funct2Call"]()
Peter
More information about the Python-list
mailing list