execfile() on file subclass or string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Brano Zarnovican

    #1

    execfile() on file subclass or string

    Hi !

    I have a python script represented by a string.
    I need to execute it in a context. 'exec' does
    the job, but doesn't display the filename in
    tracebacks. 'execfile' is displaying the filename
    but it can only exec a script in a filesystem.

    I have tried:
    - to give exec a filename, like:

    exec script_content in dict({'__file__ ':'bla.py'})

    => didn't work (neighter with __name__)

    - create an in-memory file subclassing 'file'

    class memfile(file):
    ..
    def read(self)..

    => also pointless as 'execfile' doesn't accept a file
    only a filename

    Can you help me ?
    The only problem I need to resolve is that I don't see
    the script name in tracebacks.

    Thanks,

    BranoZ

    PS: The script didn't came from the filesystem, but I know
    it's content and a name.

  • Do Re Mi chel La Si Do

    #2
    Re: execfile() on file subclass or string

    Hi !


    little idea :
    You can save the string, in temp-directory (see tempfile module), then,
    use execfile


    Michel Claveau


    Comment

    • Fredrik Lundh

      #3
      Re: execfile() on file subclass or string

      Brano Zarnovican wrote:
      [color=blue]
      > I have a python script represented by a string.
      > I need to execute it in a context. 'exec' does
      > the job, but doesn't display the filename in
      > tracebacks. 'execfile' is displaying the filename
      > but it can only exec a script in a filesystem.
      >
      > I have tried:
      > - to give exec a filename, like:
      >
      > exec script_content in dict({'__file__ ':'bla.py'})
      >
      > => didn't work (neighter with __name__)[/color]

      compile the script first, and execute the resulting code object:
      [color=blue][color=green][color=darkred]
      >>> exec compile("code", "filename", "exec")[/color][/color][/color]
      Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "filename", line 1, in ?
      NameError: name 'code' is not defined

      </F>



      Comment

      • Brano Zarnovican

        #4
        Re: execfile() on file subclass or string

        > exec compile("code", "filename", "exec")

        Thanks for the tip!
        Works great!

        BranoZ

        Comment

        Working...