Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve case in ConfigParser?

I have tried to use Python's ConfigParser module to save settings. For my app it's important that I preserve the case of each name in my sections. The docs mention that passing str() to ConfigParser.optionxform() would accomplish this, but it doesn't work for me. The names are all lowercase. Am I missing something?

<~/.myrc contents> [rules] Monkey = foo Ferret = baz 

Python pseudocode of what I get:

import ConfigParser,os  def get_config():    config = ConfigParser.ConfigParser()    config.optionxform(str())     try:         config.read(os.path.expanduser('~/.myrc'))         return config     except Exception, e:         log.error(e)  c = get_config()   print c.options('rules') [('monkey', 'foo'), ('ferret', 'baz')] 
like image 520
pojo Avatar asked Oct 23 '09 07:10

pojo


People also ask

Is Configparser case sensitive?

By default, section names are case sensitive but keys are not 1.

What is Configparser Configparser ()?

ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.

Is Configparser built in Python?

configparser comes from Python 3 and as such it works well with Unicode. The library is generally cleaned up in terms of internal data storage and reading/writing files.


2 Answers

The documentation is confusing. What they mean is this:

import ConfigParser, os def get_config():     config = ConfigParser.ConfigParser()     config.optionxform=str     try:         config.read(os.path.expanduser('~/.myrc'))         return config     except Exception, e:         log.error(e)  c = get_config()   print c.options('rules') 

I.e. override optionxform, instead of calling it; overriding can be done in a subclass or in the instance. When overriding, set it to a function (rather than the result of calling a function).

I have now reported this as a bug, and it has since been fixed.

like image 141
Martin v. Löwis Avatar answered Oct 01 '22 09:10

Martin v. Löwis


For me worked to set optionxform immediately after creating the object

config = ConfigParser.RawConfigParser() config.optionxform = str 
like image 24
ulitosCoder Avatar answered Oct 01 '22 08:10

ulitosCoder