[Tutor] Re: Config Files and Thankx (Reading Numerical Data)

Andrei project5 at redrival.net
Tue Jul 6 20:53:11 CEST 2004


Karthikesh Raju wrote on Tue, 6 Jul 2004 13:20:02 +0300:

> Thankx for the responses for my earlier mail. Somehow, i did not get
> the responses, but when i checked the archives i found them. It was
> quite useful (Andrei's esp).

Glad it helped.

> Now suppose i have a config file like say
> [userful]
> no_of_sources    10
> no_of_users      20
<snip>

If you add equal signs or colons in between name and value, you can use the
ConfigParser module to parse what is essential an INI file. E.g. you can
use the sections() method to get all categories [blabla]. ConfigParser has
built-in conversion, e.g. the getint() method which returns an integer. 

> a) How do i convert the numbers to int (numerals) and not string

Use int(sometext). Or use the appropriate method provided by the
ConfigParser module.

> b) can i do math inside a config file

Um... not as such and I'm not sure that's a very good idea anyway. You can
use eval() when reading the data, so if e.g. you have a configuration entry
which says:

[section]
c=5+6

you could read the value of c as string and say something along the lines:

  settings['c'] = eval(settings['c'])

However, don't do this if you don't fully trust the code in the config
file. If there is a chance that a malicious user could get to it and modify
it, eval()-ing it is dangerous, because you're basically giving that
malicious user the right to run arbitrary code on your machine. 
Note that if the persons who have access to the config files also by
definition have access to the program, there is no extra danger from eval -
if one of these persons is malicious, he could modify your .py directly
instead of messing around with the config file.

> c) suppose i have 4 sections, and read then in dictionaries as
> 
> config{'section1':{},'section2':{}, 'section3':{},'section4':{}}
> 
> and call this with:
> 
> source, jammer = readConfig('config.file'),
> 
> i should be able to get just section1 and section2 in source and jammer

That wouldn't work, because readConfig would have to return a 2-tuple, not
a dictionary (dictionaries can't be unpacked). But you could rewrite
readConfig to return a tuple - it would need more parameters though. Or, of
course, you could use ConfigParser (hint, hint ;). Never do yourself what
the Python batteries can do for you.

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.



More information about the Tutor mailing list