includes on an exec?
Brent Turner
brent.turner at clarisay.com
Thu Oct 23 15:44:40 EDT 2003
"berklee just berklee" <berklee(@)hotmail.com> wrote in message news:<Q5Slb.32930$Ol.654252 at read1.cgocable.net>...
> I want to run a code module by loading the code as any other text file, and
> then calling exec() on its contents.
>
> For some reason, Python doesn't seem to find the includes that are
> referenced in the script being called.
>
> I tried dropping it into the Python 'lib' folder, and in the same folder as
> my script, neither seems to work?
>
> Any suggestions?
Here is some code that I use:
# class for compiling and using python code (Text)
class PyCode:
def __init__(self):
self.code = None
self.module = None
# compile module from file
def fromFile(self, filename):
f = open(filename, 'r')
text = f.read()
f.close()
return self.CompileModule(GetFilenameBase(filename), text)
# compile to a module (with name moduleName) from text (code)
def CompileModule(self,moduleName, text):
# remove all cariage returns (compile does not like it)
text = string.replace(text, '\r', '')
# make sure there is a line feed at the end
# compile does not like it if there is not
if text and text[-1] != '\n':
text += '\n'
co = compile(text, '', 'exec')
# create a new module and exec the code object into the dict
import imp
codeModule = imp.new_module(moduleName)
exec co in codeModule.__dict__
return codeModule
# clear the compiled code
def SetCode(self, code, bCheckDiff = 1):
code = string.strip(code)
if (bCheckDiff and code != self.code) or not bCheckDiff:
self.code = code
if self.code:
self.module = self.CompileModule('CodeEdit', self.code)
else:
self.module = None
# exec code in the module
def execCode(self, code_str):
exec code_str in self.module.__dict__
********************************************************
to Use:
pc = PyCode()
module = pc.fromFile('Test.py')
# now module should act as any other module object
Hope this Helps,
Brent
More information about the Python-list
mailing list