如何用Python修改配置文件
我正在尝试用Python修改一个配置文件。我想知道怎么能在Python中做到类似于多个sed命令的效果,格式是这样的:
sed -ci 's/ServerTokens OS/ServerTokens Prod/' /etc/httpd/conf/httpd.conf
在Python中最有效率的方法是什么?我现在的做法是:
with open("httpd.conf", "r+") as file:
tmp = []
for i in file:
if '#ServerName' in i:
tmp.append(i.replace('#ServerName www.example.com', 'ServerName %s' % server_name , 1))
elif 'ServerAdmin' in i:
tmp.append(i.replace('root@localhost', webmaster_email, 1))
elif 'ServerTokens' in i:
tmp.append(i.replace('OS', 'Prod', 1))
elif 'ServerSignature' in i:
tmp.append(i.replace('On', 'Off', 1))
elif 'KeepAlive' in i:
tmp.append(i.replace('Off', 'On', 1))
elif 'Options' in i:
tmp.append(i.replace('Indexes FollowSymLinks', 'FollowSymLinks', 1))
elif 'DirectoryIndex' in i:
tmp.append(i.replace('index.html index.html.var', 'index.php index.html', 1))
else:
tmp.append(i)
file.seek(0)
for i in tmp:
file.write(i)
这样做太复杂了,因为我其实可以直接用subprocess和sed来完成。有什么建议吗?
1 个回答
1
在Python中,你可以用正则表达式,方法和在sed中很相似。只需要使用Python的正则表达式库。你可能会对re.sub()这个方法感兴趣,它的功能和你例子中的sed的s
命令是一样的。
如果你想高效地完成这个操作,可能每行只需要运行一次替换命令,如果没有变化就跳过,这和你例子中的做法类似。为了实现这个,你可以用re.subn
代替re.sub
,或者结合使用re.match和匹配到的组。
下面是一个例子:
import re
server_name = 'blah'
webmaster_email = 'blah@blah.com'
SUBS = ( (r'^#ServerName www.example.com', 'ServerName %s' % server_name),
(r'^ServerAdmin root@localhost', 'ServerAdmin %s' % webmaster_email),
(r'KeepAlive On', 'KeepAlive Off')
)
with open("httpd.conf", "r+") as file:
tmp=[]
for i in file:
for s in SUBS:
ret=re.subn(s[0], s[1], i)
if ret[1]>0:
tmp.append(ret[0])
break
else:
tmp.append(i)
for i in tmp:
print i,