includes on an exec?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • berklee just berklee

    includes on an exec?

    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?


  • Brent Turner

    #2
    Re: includes on an exec?

    "berklee just berklee" <berklee(@)hotm ail.com> wrote in message news:<Q5Slb.329 30$Ol.654252@re ad1.cgocable.ne t>...[color=blue]
    > 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?[/color]

    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.CompileMod ule(GetFilename Base(filename), text)

    # compile to a module (with name moduleName) from text (code)
    def CompileModule(s elf,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.__di ct__
    return codeModule

    # clear the compiled code
    def SetCode(self, code, bCheckDiff = 1):
    code = string.strip(co de)
    if (bCheckDiff and code != self.code) or not bCheckDiff:
    self.code = code
    if self.code:
    self.module = self.CompileMod ule('CodeEdit', self.code)
    else:
    self.module = None

    # exec code in the module
    def execCode(self, code_str):
    exec code_str in self.module.__d ict__


    *************** *************** *************** ***********
    to Use:
    pc = PyCode()
    module = pc.fromFile('Te st.py')
    # now module should act as any other module object

    Hope this Helps,
    Brent

    Comment

    Working...