By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,846 Members | 1,872 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,846 IT Pros & Developers. It's quick & easy.

Execute external code and get return value

P: n/a
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
Sep 29 '06 #1
Share this Question
Share on Google+
4 Replies


P: n/a
Michele Petrazzo wrote:
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
Sep 29 '06 #2

P: n/a
Michele Petrazzo wrote:

Auto reply:
I find this: http://tinyurl.com/nwbpk
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
Sep 29 '06 #3

P: n/a
Peter Otten wrote:
Michele Petrazzo wrote:
>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.
Peter
Thanks,
Michele
Sep 29 '06 #4

P: n/a
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

Sep 29 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.