[Tutor] Question about ConfigParser

Dave Kuhlman dkuhlman at rexx.com
Sun Jan 7 00:26:45 CET 2007


On Sat, Jan 06, 2007 at 10:40:27PM +0100, Jan Erik Mostr??m wrote:
> I'm trying to use ConfigParser for the first time and I'm 
> missing something. I have this code
> 
> import ConfigParser
> import datetime
> 
> conf = ConfigParser.ConfigParser()
> 
> conf.add_section('general')
> conf.set( 'general', 'revision', 0 )
> conf.set( 'general', 'date', 
> datetime.datetime.now().strftime("%Y-%m-%d") )
> conf.set( 'general', 'currentsetname', '' )
> conf.set( 'general', 'incrementalcount', 0 )
> conf.add_section( "Hello world" )
> conf.set( "Hello world", 'apa', 3298 )
> 
> print conf.sections()
> print conf.items('general')
> 
> #for debug_repos in conf.sections():
> #   print debug_repos #, conf.items( debug_repos )
> 
> 
> When I run this I get the following result
> 
> ['Hello world', 'general']
> Traceback (most recent call last):
>    File "backup.py", line 15, in <module>
>      print conf.items('general')
>    File 
> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", 
> line 557, in items
>      for option in options]
>    File 
> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py", 
> line 565, in _interpolate
>      if "%(" in value:
> TypeError: argument of type 'int' is not iterable
> 
> What am I missing with the items call?

Here is a clue -- If you write out your configuration to a file
with something like:

    conf.write(sys.stdout)

and store it in a file.  Then, if you read it in, all seems to work
well.  For example, the following function:

    def test2():
        conf = ConfigParser.ConfigParser()
        conf.read('test1.conf')
        print 'options -- general:', conf.options('general')
        opt1 = conf.get('general', 'date')
        print 'opt1:', opt1
        print conf.items('general')

executes without error.  Can you guess why?

Note that in your original code, the default values for some of
your options have type int.  If you change those to strings, then
the error goes away.  For example, change:

    conf.set( 'general', 'revision', 0 )

to:

    conf.set( 'general', 'revision', "0" )

Writing it to a file does this conversion and hides the error.

It's sort of hidden, but note the restriction to string values in
the docs on the set method:

    set(section, option, value)
      If the given section exists, set the given option to the specified
      value; otherwise raise NoSectionError. While it is possible to use
      RawConfigParser (or ConfigParser with raw parameters set to true)
      for internal storage of non-string values, full functionality
      (including interpolation and output to files) can only be achieved
      using string values. New in version 1.6.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list