execfile() on file subclass or string

B

Brano Zarnovican

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.
 
D

Do Re Mi chel La Si Do

Hi !


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


Michel Claveau
 
F

Fredrik Lundh

Brano said:
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__)

compile the script first, and execute the resulting code object:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "filename", line 1, in ?
NameError: name 'code' is not defined

</F>
 
B

Brano Zarnovican

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

Thanks for the tip!
Works great!

BranoZ
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top