3

我想使用 python 修改 samba 配置文件。这是我的代码

from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read( '/etc/samba/smb.conf' )

for section in parser.sections():
    print section
    for name, value in parser.items( section ):
        print '  %s = %r' % ( name, value )

但是配置文件包含选项卡,是否有可能忽略选项卡?

ConfigParser.ParsingError: File contains parsing errors: /etc/samba/smb.conf
    [line 38]: '\tworkgroup = WORKGROUP\n'
4

2 回答 2

5

试试这个:

from StringIO import StringIO

data = StringIO('\n'.join(line.strip() for line in open('/etc/samba/smb.conf')))

parser = SafeConfigParser()
parser.readfp(data)
...

另一种方式(感谢@mgilson 的想法):

class stripfile(file):
    def readline(self):
        return super(FileStripper, self).readline().strip()

parser = SafeConfigParser()
with stripfile('/path/to/file') as f:
    parser.readfp(f)
于 2012-10-10T14:43:35.143 回答
5

我会创建一个小的代理类来提供解析器:

class FileStripper(object):
    def __init__(self,f):
        self.fileobj = open(f)
        self.data = ( x.strip() for x in self.fileobj )
    def readline(self):
        return next(self.data)
    def close(self):
        self.fileobj.close()

parser = SafeConfigParser()
f = FileStripper(yourconfigfile)
parser.readfp(f)
f.close()

您甚至可以做得更好(允许多个文件,完成后自动关闭等):

class FileStripper(object):
    def __init__(self,*fnames):
        def _line_yielder(filenames):
            for fname in filenames:
                with open(fname) as f:
                     for line in f:
                         yield line.strip()
        self.data = _line_yielder(fnames)

    def readline(self):
        return next(self.data)

它可以这样使用:

parser = SafeConfigParser()
parser.readfp( FileStripper(yourconfigfile1,yourconfigfile2) )
#parser.readfp( FileStripper(yourconfigfile) ) #this would work too
#No need to close anything :).  Horray Context managers!
于 2012-10-10T14:49:47.117 回答