Is there any solution to force the RawConfigParser.write() method to export the config file with an alphabetical sort?
Even if the original/loaded config file is sorted, the module mixes the section and the options into the sections arbitrarily, and is really annoying to edit manually a huge unsorted config file.
PD: I'm using python 2.6
I was looking into this for merging a .gitmodules doing a subtree merge with a supermodule -- was super confused to start with, and having different orders for submodules was confusing enough haha.
Using GitPython helped alot:
I was able to solve this issue by sorting the sections in the ConfigParser from the outside like so:
This is my solution for writing config file in alphabetical sort:
Three solutions:
write()
(just copy this method from the original source and modify it).write()
.See this article for a ordered dict or maybe use this implementation which preserves the original adding order.
The first method looked as the most easier, and safer way.
But, after looking at the source code of the ConfigParser, it creates an empty built-in dict, and then copies all the values from the "second parameter" one-by-one. That means it won't use the OrderedDict type. An easy work around can be to overload the CreateParser class.
It leaves only one flaw open... namely in ConfigParser.items(). odict doesn't support
update
andcomparison
with normal dicts.Workaround (overload this function too):
Other solution to the items issue is to modify the
odict.OrderedDict.update
function - maybe it is more easy than this one, but I leave it to you.PS: I implemented this solution, but it doesn't work. If i figure out, ConfigParser is still mixing the order of the entries, I will report it.
PS2: Solved. The reader function of the ConfigParser is quite idiot. Anyway, only one line had to be changed - and some others for overloading in an external file:
Trust me, I didn't wrote this thing. I copy-pasted it entirely from ConfigParser.py
So overall what to do?
OrderedRawConfigParser
class for you)cfg = utils.OrderedRawConfigParser(odict.OrderedDict())
PS3: The problem I solved here is only in Python 2.5. In 2.6 there is already a solution for that. They created a second custom parameter in the
__init__
function, which is a custom dict_type.So this workaround is needed only for 2.5