【问题标题】:How to modify configuration file with Python如何使用 Python 修改配置文件
【发布时间】: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 代替。有什么建议?

【问题讨论】:

标签: python replace sed


【解决方案1】:

您可以在 Python 中使用正则表达式,其方式与在 sed 中执行此操作的方式非常相似。只需使用Python regular expressions library。您可能对 re.sub() 方法感兴趣,它与您示例中使用的 sed 的 s 命令等效。

如果您想有效地执行此操作,您可能必须每行只运行一个替换命令,如果它被更改则跳过它,类似于您在示例代码中执行此操作的方式。为了实现这一点,您可以使用 re.subn 而不是 re.subre.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,

【讨论】:

  • 愿意与 re.sub 或 resubn 分享一个示例吗?这让我很困惑
猜你喜欢
  • 1970-01-01
  • 2021-04-24
  • 2015-12-24
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
相关资源
最近更新 更多