如何用Python修改配置文件

如何用Python修改配置文件,python,replace,sed,Python,Replace,Sed,我正在尝试使用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:

我正在尝试使用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中使用正则表达式非常类似。就用吧。您可能对该方法感兴趣,它与示例中使用的sed的
s
命令相当

如果您想有效地执行此操作,可能每行只需运行一个替换命令,如果它被更改,则跳过它,类似于在示例代码中执行此操作的方式。为了实现这一点,您可以使用
re.subn
而不是
re.sub
或与匹配的组组合使用

下面是一个例子:

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,

为什么不使用subprocess和sed呢?很有趣。如果可以选择使用python,您一定要使用python吗?python与sed相当:使用python配置解析器,即。让事情变得更容易@PythonNoob:文档上说,“以“#”或“;”开头的行被忽略,可能用于提供注释。”要不要与re.sub或resubn分享一个例子?这让我很困惑