How to eval a file
Carl Banks
imbosol-1045933235 at aerojockey.com
Sat Feb 22 12:20:33 EST 2003
Bj?rn Lindberg wrote:
> I'm writing a program with a "configuration file" if you will, that
> looks something like this:
>
> --------------------------------
> collection = '''Abba %sdabba'''
> topic = '''Gucko %s'''
> --------------------------------
>
> I have trouble getting this information into Python. I was hoping I
> could read this file as a string and then eval() it, to get the
> variables collection & topic set to the respective strings in the
> local context. Ie, in a class method:
>
> def read_file(name):
> f = open(name, 'r')
> string = f.read()
> eval(string)
>
> self.collection = collection
> self.topic = topic
> ...
>
> f.close()
>
> This gives the following error message:
>
> File "<string>", line 3
> collection = '''<h3%s</h3>'''
> ^
> SyntaxError: invalid syntax
eval requires an expression (an expression is something you can pass
as an argument to a function). You are trying to execute statements
that are not expressions (you can't pass an assignment into a
function); therefore, you need to use the exec statement.
> So I tried using execfile(name) instead, but that doesn't work
> either.
It should work with execfile (unless, of course, you have an error in
your input file). It wouldn't work with evalfile.
Also, remember that you should be careful when using exec and its
variants. A person could put malicious code into the conffile, and
you should be aware of that.
--
CARL BANKS
More information about the Python-list
mailing list