How to eval a file

Björn Lindberg d95-bli at nada.kth.se
Sat Feb 22 23:51:17 EST 2003


Alexander Schmolck <a.schmolck at gmx.net> writes:

> >     def read_file(name):
> 
> You mean ``def read_file(self, name):`` I take it?

Yes.

> The code is not only broken, it's also a bad way to set about it,
> e.g. why would you want to mess up your functions namespace? Think
> of what would happen if the configuration file contained a name you
> use (e.g. "f", "self" etc.).  Also, if you don't have control over
> the file's contents, someone might just enter code that formats your
> harddisk.

The application will run as a CGI script, so it won't have permissions
to do anything to my hard drive. Also, the person who sets up the
application is the one expected to edit the configuration file, so
there is no reason to suspect it to be maliciously composed.

> This is because eval only works for expressions (i.e. something that
> returns a value), assignment ('=') is a statement (as are 'if',
> 'for' etc.). So
> 
>   f = eval('3 + 4')
> 
> will work fine.
> 
>   eval('f = 3 + 4')
> 
> won't. If you want to execute arbitrary code (and not just expressions), use
> exec or execfile.

I see now. BTW, isn't it a bit strange that the eval syntax is
eval(<expr>), whereas exec is written without parantheses, exec
"<statement>"?

> > So I tried using execfile(name) instead, but that doesn't work
> > either. 
> 
> It does, you're just not using it correctly (and don't give many hints as to
> what exactly you did). Try this [UNTESTED]:
>   
>   namespace = {}
>   execfile(filename, namespace)
>   self.collection = namespace['collection']

Ah, I see now. I thought that by just doing "execfile(filename)", the
variables would automagically appear in the local namespace. The
environment argument I thought was for /providing/ the exec'd file
with an environment only.

<snip>

> > Is there another way?
> 
> Yes. Doing it properly (without any exec*s). If your configuration file just
> looks like
> 
>  var1 = '''some string'''
>  var2 = '''some other string'''
> 
> then parse it, it isn't particularly difficult.

You are right. I was trying to take advantage of the fact that I am
using a very high level language. But still, there are fewer security
implications and more error checking by parsing it manually. I think I
will use the execfile() solution for now, and when it gets closer to
being finished, I will write a proper parser instead.


Björn




More information about the Python-list mailing list