我正在尝试使用 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 代替。有什么建议么?
最佳答案
您可以在 Python 中使用正则表达式,就像在 sed 中使用正则表达式一样。只需使用 Python regular expressions library .您可能对 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,
关于python - 如何用Python修改配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835618/