By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,035 Members | 1,388 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,035 IT Pros & Developers. It's quick & easy.

execfile() on file subclass or string

P: n/a
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.

Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Hi !
little idea :
You can save the string, in temp-directory (see tempfile module), then,
use execfile
Michel Claveau
Jul 18 '05 #2

P: n/a
Brano Zarnovican wrote:
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:
exec compile("code", "filename", "exec")

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "filename", line 1, in ?
NameError: name 'code' is not defined

</F>

Jul 18 '05 #3

P: n/a
> exec compile("code", "filename", "exec")

Thanks for the tip!
Works great!

BranoZ

Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.