2008-05-03
Dynamic Code Execution in Python
Some might remember my earlier experiments in dynamic code execution in Perl. Here is a simple recipe to demonstrate a similar concept in Python:
Hopefully you will find this useful. In theory you can now execute snippets of code from sources like databases and files. I think this has potential for some distributed processing framework :-)
1 #!/usr/bin/python
2
3 import new
4
5 def importCode(code, name, add_to_sys_modules=False):
6 # code can be any object containing code: a string, a file object, or
7 # a compiled code object. Returns a new module object initialized
8 # by dynamically importing the given code, and optionally adds it
9 # to sys.modules under the given name.
10 #
11 module = new.module(name)
12 if add_to_sys_modules:
13 import sys
14 sys.modules[name] = module
15 exec code in module.__dict__
16 return module
17
18 code = """
19 def testFunc( ):
20 print "spam!"
21 class testClass(object):
22 def testMethod(self):
23 print "eggs!"
24 """
25
26 m = importCode( code, "test" )
27 m.testFunc( )
28 o = m.testClass( )
29 o.testMethod( )
Hopefully you will find this useful. In theory you can now execute snippets of code from sources like databases and files. I think this has potential for some distributed processing framework :-)
Comments:
<< Home
Works very nicely, but, variables/objects don't appear to be available, for example if you were to do this with tkinter and you try to access a text box called xxxxx you get an error xxxxx is not defined, same with variables even if you attempt to make them global inside of the imported module.
The following is a "snippet" that my test application reads and then executes. If I could solve the variable issue then this process of yours will be very handy.
# python snippet -
def testFunc( ):
print " testFunc runs ok "
print " but can't use variables from the parent program "
#global oem_c
#print "latstring " + oem_c.latString
# global makes no difference posn_lon_text is not defined
global posn_lon_text
mytext = posn_lon_text.get(0.0, END)
print "lat:" + mytext
class testClass(object):
def testMethod(self):
# this works fine if it doesn't die from errors in TestFunc
print "testClass!"
Post a Comment
The following is a "snippet" that my test application reads and then executes. If I could solve the variable issue then this process of yours will be very handy.
# python snippet -
def testFunc( ):
print " testFunc runs ok "
print " but can't use variables from the parent program "
#global oem_c
#print "latstring " + oem_c.latString
# global makes no difference posn_lon_text is not defined
global posn_lon_text
mytext = posn_lon_text.get(0.0, END)
print "lat:" + mytext
class testClass(object):
def testMethod(self):
# this works fine if it doesn't die from errors in TestFunc
print "testClass!"
<< Home