473,587 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ConfigParser

Regards.

Since sections in CongiParser files are delimited by [ and ], why
there is not an escape (and unescape) function for escaping
&, [, and ] characters to &, [ and ] ?


Thanks Manlio Perillo
Jul 18 '05 #1
11 4879
On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo
<NO************ ******@libero.i t> wrote:
Regards.

Since sections in CongiParser files are delimited by [ and ], why
there is not an escape (and unescape) function for escaping
&, [, and ] characters to &amp;, &lbrack; and &rbrack; ?


Thanks Manlio Perillo


just subclass from ConfigParser and add the functionality youself

somthing like:
=== cut here ===
from ConfigParser import ConfigParser
class MyConfigParser( ConfigParser):
def get(self, section, option, raw=False, vars=None): # override
the get() method of super
"""get(sect ion, option, [raw=False], [vars=None]) --> String"""
repl = [('&lbrack;','['),
('&rbrack;',']'),
] # extent as
much as U like
t = ConfigParser.ge t(self, section, option, raw, vars) # call the
get of super
for x,y in repl: t=t.replace(x,y ) # do the
replace stuff
return t

if __name__=="__ma in__":
"""test"""
import os
open('test.$$$' ,'w').write('[test]\nopt1=Hello&lb rack;Ivo
Woltring&rbrack ;\n')
ini = MyConfigParser( )
ini.read('test. $$$')
print ini.get('test', 'opt1')
os.unlink('test .$$$')
=== End Cut ===

you can ofcourse do this in reverse for the write function so as not
to have to write the &lbrack; etc. yourself.

Cheerz,
Ivo Woltring
Jul 18 '05 #2
On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo
<NO************ ******@libero.i t> wrote:
Regards.

Since sections in CongiParser files are delimited by [ and ], why
there is not an escape (and unescape) function for escaping
&, [, and ] characters to &amp;, &lbrack; and &rbrack; ?


Thanks Manlio Perillo

Next try with attachment MyConfigParser. py
Just save and run to see
Cheerz,
Ivo.
Jul 18 '05 #3
On Wed, 10 Nov 2004 15:39:42 +0100, Ivo Woltring <Py****@IvoNet. nl>
wrote:
On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo
<NO*********** *******@libero. it> wrote:
Regards.

Since sections in CongiParser files are delimited by [ and ], why
there is not an escape (and unescape) function for escaping
&, [, and ] characters to &amp;, &lbrack; and &rbrack; ?


Thanks Manlio Perillo


just subclass from ConfigParser and add the functionality youself

Actually I have written two functions:

def escape(data):
"""Escape &, [ and ] a string of data.
"""
data = data.replace("& ", "&amp;")
data = data.replace("[", "&lbrack;")
data = data.replace("]", "&rbrack;")

return data

def unescape(data):
"""Unescape &amp;, &lt;, and &gt; in a string of data.
"""
data = data.replace("& lbrack;", "[")
data = data.replace("& rbrack;", "]")

# must do ampersand last
return data.replace("& amp;", "&")
Maybe also '\n' to &nl; translation should be performed.


Thanks and regards Manlio Perillo
Jul 18 '05 #4
On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo
<NO************ ******@libero.i t> wrote:
Regards.

Since sections in CongiParser files are delimited by [ and ], why
there is not an escape (and unescape) function for escaping
&, [, and ] characters to &amp;, &lbrack; and &rbrack; ?


Thanks Manlio Perillo


By the way I did some testing because i have a similar thing going on
right now. I found out that

[section]
option = [Ivo Woltring]

is valid and does not have to be translated to
[section]
option = &lbrack;Ivo Woltring&rbrack ;

to work.
so my current class is a bit unnessesary:

#
# IniFile extents the ConfigParser with my own functions
#
__author__ = "Ivo Woltring"
__version__ = "01.00"
__copyright__ = "Copyright (c) 2004 Ivo Woltring"
__license__ = "Python"

from ConfigParser import *

class IniFile(ConfigP arser):
"""IniFile
Is an extention on the ConfigParser class.
It overrulles the write method so it can write directly to a file
provided as
a parameter. The whole filehandling is done by the IniFile.write(f p)
method.
"""
def __init__(self, defaults=None):
ConfigParser.__ init__(self, defaults) # supers init
self.replace = [('&lbrack;','['),
('&rbrack;',']'),
]

def write(self,fp):
"""write(filena me) --> written file"""
try:
f = open(fp,'w')
except IOError:
raise IOError
#ConfigParser.w rite(self,f)
self._write(f)
f.close()

def _replace(self, txt ,reverse=False) :
"""Replace the self.replace stuff"""
for source, target in self.replace:
if reverse: txt=txt.replace (target, source)
else: txt=txt.replace (source, target)
return txt

def get(self, section, option, raw=False, vars=None): # override
the get() method of super
"""get(sect ion, option, [raw=False], [vars=None]) --> String
this get() is an extention on the origional ConfigParser.ge t()
This one translates html style '&lbrack;' to '[' etc.
"""
if raw:
return ConfigParser.ge t(self, section, option, raw, vars) # call
the get of super
return self._replace(C onfigParser.get (self, section, option, raw,
vars))

def _write(self, fp):
"""Write an .ini-format representation of the configuration
state."""
if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
for (key, value) in self._defaults. items():
fp.write("%s = %s\n" %
(key, self._replace(s tr(value).repla ce('\n',
'\n\t'), reverse=True)))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
if key != "__name__":
fp.write("%s = %s\n" %
(key,
self._replace(s tr(value).repla ce('\n', '\n\t'), reverse=True)))
fp.write("\n")

if __name__=="__ma in__":
import sys,os
p = IniFile()
p.add_section(' section')
p.set('section' ,'option','[Ivo Woltring]')
p.write(os.path .splitext(sys.a rgv[0])[0]+'.ini')
print p.get('section' ,'option')
print p.get('section' ,'option', raw=True)
raw_input('Pres s enter to continue...')
have fun... I do,

Cheerz, Ivo.

Jul 18 '05 #5
On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo
<NO************ ******@libero.i t> wrote:
Regards.

Since sections in CongiParser files are delimited by [ and ], why
there is not an escape (and unescape) function for escaping
&, [, and ] characters to &amp;, &lbrack; and &rbrack; ?


Thanks Manlio Perillo


another discovery:

the get() DOES translate &lbrack; etc back to '[' etc, so it seameth
to me that the whole question is mute ;-))

Ivo.
Jul 18 '05 #6
Damn I made a mistake...
The translation IS needed (so sorry ;-(()

here a functional class:

Jul 18 '05 #7
"Ivo Woltring" <Py****@IvoNet. nl> wrote in message
news:35******** *************** *********@4ax.c om...
<snip>
...the whole question is mute ;-))

Ivo.


The word you are looking for is "moot", not "mute" - this is actually a
common word misuse (known as a "malapropis m") even for native English
speakers. :)

Pedantical-ly yours,
-- Paul
Jul 18 '05 #8
On Wed, 10 Nov 2004 21:04:55 +0100, Ivo Woltring <Py****@IvoNet. nl>
wrote:
On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo
<NO*********** *******@libero. it> wrote:
Regards.

Since sections in CongiParser files are delimited by [ and ], why
there is not an escape (and unescape) function for escaping
&, [, and ] characters to &amp;, &lbrack; and &rbrack; ?


Thanks Manlio Perillo


By the way I did some testing because i have a similar thing going on
right now. I found out that

[section]
option = [Ivo Woltring]

is valid and does not have to be translated to
[section]
option = &lbrack;Ivo Woltring&rbrack ;


Yes, I have discovered this too.
But my problem is with section names.

Thanks and regards Manlio Perillo
Jul 18 '05 #9
On Wed, 10 Nov 2004 21:09:39 +0100, Ivo Woltring <Py****@IvoNet. nl>
wrote:
On Wed, 10 Nov 2004 10:39:27 GMT, Manlio Perillo
<NO*********** *******@libero. it> wrote:
Regards.

Since sections in CongiParser files are delimited by [ and ], why
there is not an escape (and unescape) function for escaping
&, [, and ] characters to &amp;, &lbrack; and &rbrack; ?


Thanks Manlio Perillo


another discovery:

the get() DOES translate &lbrack; etc back to '[' etc, so it seameth
to me that the whole question is mute ;-))

What version are you using?
In Python 2.3.3 get does not handles &lbrack; (or I did not understand
what you are saying).

Thanks and regards Manlio Perillo
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2618
by: Greg Krohn | last post by:
I'm trying to subclass ConfigParser so I can use a custom __read method (the custom format doesn't conform to RFC 822) when needed. Needless to say, it's not working as expected. In the following code, I bind __read_ini to __read and override __read so it can choose between __read_ini and __read_custom. But it seems that __read_custom never...
1
1817
by: Martin Maney | last post by:
Summary: with batteries like these, get a longer extension cord? <transcript from interactive session> Python 2.2.1 (#1, Sep 7 2002, 14:34:30) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ConfigParser import ConfigParser >>> cp = ConfigParser()
2
4292
by: Roy H. Berger | last post by:
If I want to subclass ConfigParser and changed the optionxform method to not return things in lower case wouldn't I just need the following code in my subclasss module? from ConfigParser import * class MyConfigParser(ConfigParser): def __init__(self, defaults=None): ConfigParser.__init__(self, defaults)
6
6772
by: Matthew Barnes | last post by:
I'm considering submitting a patch for Python 2.4 to allow environment variable expansion in ConfigParser files. The use cases for this should be obvious. I'd like to be able to specify something like the following in a configuration file: data_file=${HOME}/mydata.dat ....(where HOME=/home/matt) and have ConfigParser automatically...
2
1694
by: rzed | last post by:
I am working with PythonCard in one of my apps. For its purposes, it uses an .ini file that is passed to ConfigParser. For my app, I also need configuration information, but for various reasons, I'd rather use a syntax that ConfigParser can't handle. I know I can maintain two separate configuration files, and if I have to I will, but I'd...
10
11773
by: Terry Carroll | last post by:
It looks like ConfigParser will accept a list to be writing to the *.ini file; but when reading it back in, it treats it as a string. Example: ############################### import ConfigParser def whatzit(thingname, thing): print thingname, "value:", thing print thingname, "length:", len(thing)
1
2011
by: pipehappy | last post by:
Hello everyone: I came across the module ConfigParser and can use it correctly. import ConfigParser fp = open('test.cfg','w+') config = ConfigParser.ConfigParser() config.readfp(fp) config.add_section('test') config.set('test', 'haha', 'hehe')
4
1860
by: Danil Dotsenko | last post by:
Wrote a little "user-friedly" wrapper for ConfigParser for a KDE's SuperKaramba widget. (http://www.kde-look.org/content/show.php?content=32185) I was using 2.4.x python docs as reference and ConfigParser.read('non-existent-filename') returns in 2.4.x One user with 2.3.x reported an error stemming from my use of...
4
14164
by: Phoe6 | last post by:
Hi, I have a configfile, in fact, I am providing a configfile in the format: Name: Foo Author: Bar Testcases: tct123
0
7915
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7843
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8205
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7967
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6619
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5712
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3840
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.