Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop ConfigParser adding spaces to delims after upgrade from python 2.7.3 to 2.7.9

After being forced to use a later version of python, ConfigParser now insists on adding spaces to each side of any delims when modifying a configuration file.

e.g. setting=90 becomes: setting = 90

This was not the behavior in the earlier version, and I cannot find a way of controlling this behavior, can anyone help?

My test code looks like this:

import ConfigParser
import os

config   = ConfigParser.ConfigParser()
cfgfile  = '/home/osmc/bin/test/config.txt'
os.system('sudo echo "[section]" > ' + cfgfile)
os.system('sudo echo "setting=0" >> ' + cfgfile)

config.read(cfgfile)
config.set('section','setting', '1' )

with open(cfgfile, 'wb') as newcfgfile:
    config.write(newcfgfile)

Thanks in advance.

like image 339
Chris Atkinson Avatar asked Sep 16 '25 01:09

Chris Atkinson


2 Answers

I ran into this problem to and I came up with an additional solution as posted here.

  • I didn't want to replace the function as future versions of Python might change the internal function structures of RawConfigParser.
  • I also didn't want to read the file back in right after it was written because that seemed wasteful

Instead I wrote a wrapper around the file object which simply replaces " = " with "=" in all lines written though it.

class EqualsSpaceRemover:
    output_file = None
    def __init__( self, new_output_file ):
        self.output_file = new_output_file

    def write( self, what ):
        self.output_file.write( what.replace( " = ", "=", 1 ) )

config.write( EqualsSpaceRemover( cfgfile ) )
like image 108
Joshua Avatar answered Sep 17 '25 14:09

Joshua


You can subclass and alter the .write method removing the spaces from either side of the =:

import ConfigParser
import os


class MyConfigParser(ConfigParser.ConfigParser):
    def write(self, fp):
        """Write an .ini-format representation of the configuration state."""
        if self._defaults:
            fp.write("[%s]\n" % ConfigParser.DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t')))
            fp.write("\n")
        for section in self._sections:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                if key == "__name__":
                    continue
                if (value is not None) or (self._optcre == self.OPTCRE):
                    key = "=".join((key, str(value).replace('\n', '\n\t')))
                fp.write("%s\n" % key)
            fp.write("\n")

config = MyConfigParser()
.....
like image 39
Padraic Cunningham Avatar answered Sep 17 '25 16:09

Padraic Cunningham