Execute external code and get return value

M

Michele Petrazzo

Hi,
I want to execute an external code, that become from a text file (pe),
call a function inside it and get its return value:

# ext_code.txt

def funct2Call():
return True

# test.py

sourcecode = open("ex_code.txt").read()
comp_code = compile(sourcecode, "My_test", "exec")

#do something like this
return_value = comp_code.funct2Call()

But I can't...

I find this:
http://tinyurl.com/nwbpk

but here, it call from the external code a function inside my code. I
want the opposite!
Is there a solution for do this?

Thanks,
Michele
 
P

Peter Otten

Michele said:
I want to execute an external code, that become from a text file (pe),
call a function inside it and get its return value:

namespace = {}
execfile("ext_code.txt", namespace)
print namespace["funct2Call"]()

Peter
 
M

Michele Petrazzo

Michele Petrazzo wrote:

Auto reply:

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"]()

Michele
 
M

Michele Petrazzo

Peter said:
Michele said:
I want to execute an external code, that become from a text file
(pe), call a function inside it and get its return value:

namespace = {} execfile("ext_code.txt", namespace) print
namespace["funct2Call"]()

Sorry, I forgot to say that "ext_code.txt" isn't a real file, but a text
become from a db, so or I create a temp file where I save the code and
pass its path to execfile, or use my post.

Thanks,
Michele
 
P

Peter Otten

Michele said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top