Exec acting like execfile

Hans Nowak wurmy at earthlink.net
Tue Aug 13 00:06:01 EDT 2002

Robert Hanlin wrote:
> Hi all,
> exec is a keyword that just expects a string, while execfile() is a
> function that accepts a filename and dicts of global and local vars. 
> So execfile() seems more powerful.  But slower because you're reading
> in a file.
> Is there any way to use exec with execfile's power?  I found that
> Python has an undocumented exec() function, but Jython doesn't.  And I
> need Jython.  How do others work around this?

Quite a few people would say, "by not using exec"... :-)

exec isn't a function, but a statement, and it can execute arbitrary code:

 >>> code = """
a = 42

print "Hello, world!"

for i in range(5):
     print a+i,
 >>> exec code
Hello, world!
42 43 44 45 46

It also supports pasisng in dictionaries for global and local variables:

 >>> a = {}
 >>> b = {}
 >>> exec code in a, b
Hello, world!
42 43 44 45 46
 >>> a
[...lots of stuff...]
 >>> b
{'a': 42, 'i': 4}

I don't know enough about Jython to tell you how to work around this, but I can 
give you the general advice that is usually given on this newsgroup when it 
comes to using exec: Ask yourself why you need it, first. Why do you want to 
execute arbitrary (?) Python code? Can an 'import' do what you want? Can some 
of Python's other dynamic and introspective features?


Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/

More information about the Python-list mailing list