【发布时间】:2014-05-15 03:54:20
【问题描述】:
我正在尝试使用 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 代替。有什么建议?
【问题讨论】:
-
为什么不使用 subprocess 和 sed?
-
有趣。如果可以的话,你一定会使用 python 吗?
-
sed 的 Python 等价物:docs.python.org/2/library/re.html#re.sub
-
使用python配置解析器,即docs.python.org/2/library/configparser.html。让事情变得更简单!
-
@PythonNoob:文档在那里说,“以 '#' 或 ';' 开头的行被忽略,可用于提供 cmets。”