我想使用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'
答案 0 :(得分: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)
答案 1 :(得分: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!