How to eval a file

Björn Lindberg d95-bli at nada.kth.se
Sat Feb 22 11:42:59 EST 2003


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

So I tried using execfile(name) instead, but that doesn't work
either. 

The only thing I can come up with now is to import the file. This has
a number of drawbacks however: (i) I would have to modify the module
search path, (ii) The file would have to be named .py, (iii) It looks
ugly (at least to me) to have an import statement inside a function,
(iv) I am not even sure it would work as I expect.

Is there another way?


Björn




More information about the Python-list mailing list