How to eval a file

Donnal Walter donnal at donnal.net
Sun Feb 23 21:00:55 EST 2003


Alex Martelli wrote:
> Donnal Walter wrote:
>    ...
> 
>>I've been thinking about making a configuration file with a syntax
>>something like this:
>>
>>{
>>   'log': './error.txt'
>>   'splash': './welcome.png'
>>   'icon': './prism.ico'
>>   'login': 'C:/prism/user.dbm'
>>   'cabinet': 'C:/prism/patient.dbm'
>>}
>>
>>Then I planned on reading the file something like this:
>>
>>         f = open(filename)
>>         txt = f.read().replace('\r\n','\n')
> 
> 
> You presumably mean to insert commas at the end of the lines, right?

Yes, of course. I have a problem with commas in dictionaries and method 
calls when they continue over to new lines.

> 
> 
>>         f.close()
>>         self.__dict__.update(eval(txt))
>>
>>Do I understand your previous reply to Björn to mean that I would still
>>be better off using ConfigParser?
> 
> 
> It's your call, of course; if you totally trust the text in the
> file (e.g. nobody's going to use __import__ tricks there...),
> then the main issue with your chosen format would seem to be
> with the difficulty of editing its syntax.  Since you don't need
> anywhere like the power of ConfigParser, while not keep it
> simple on every plane, e.g:
> 
> file contains:
> 
> log     /error.txt
> splash  /welcome.png
> icon    ./prism.ico
> login   C:/prism/user.dbm
> cabinet C:/prism/patient.dbm
> 
> and you parse it with:
> 
>     lines = [ line.split() for line in open(filename) ]
>     self.__dict__.update(dict(lines))
> 
> or something like that?

Ah, yes. I like that much better. I may also let Björn talk me into 
trying out the shlex module as well. Thanks.

Donnal







More information about the Python-list mailing list