replacement for execfile

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sun Jul 29 05:39:35 CEST 2007


On Sat, 28 Jul 2007 15:17:56 +0000, Alex Popescu wrote:

> Hi all!
> 
> From another thread (and the pointed PEP) I have found that execfile
> will not be present in Py3k. So, I am wondering what will be its
> replacement? Considering that most probably Py3k will keep eval and
> exec, this will still be possible (indeed requiring manual loading of
> the file string), so I would really appreciate some enlightning comments
> on this.

(1) Don't use eval, exec or execfile.

(2) If you're an expert, don't use eval, exec or execfile.

(3) If you're an expert, and are fully aware of the security risks, don't
use eval, exec or execfile.

(4) If you're an expert, and are fully aware of the security risks, and
have a task that can only be solved by using eval, exec or execfile, find
another solution.

(5) If there really is no other solution, you haven't looked hard enough.

(6) If you've looked REALLY hard, and can't find another solution, AND
you're an expert and are fully aware of the security risks, THEN you can
think about using eval, exec or execfile.


> Background:
> Basically this question is related to my learning process/working
> project. In this, I have the need to allow the final user to provide a
> configuration like script, but built using my API (and whatever other
> normal Python code they want). 

I hope this is running on their own computer, not yours.

If they're running it on a multi-user system, I hope they don't care about
security, because they probably don't have any now.

> For this, having execfile was a nice surprise 

Oh yes, I bet it was, in more ways than one.

> as I was able to automatically expose the API (so the end user
> doesn't need to bother about imports) and also easily execute it in the
> context I wanted.

Let's see that I understand you... you're expecting the users to write
working Python code, but you think "import module" is too hard for them?

Anyway, with all the disclaimers above, execfile is trivial:


def execfile_(filename, globals_=None, locals_=None):
    if globals_ is None:
        globals_ = globals()
    if locals_ is None:
        locals_ = globals_
    text = file(filename, 'r').read()
    exec text in globals_, locals_




-- 
Steven.




More information about the Python-list mailing list