【问题标题】:Python inplace configuration value updatePython就地配置值更新
【发布时间】:2018-01-16 00:38:40
【问题描述】:

我正在尝试使用类似于sed -i 的就地值更改来更新配置文件的“值”部分。

下面的代码显示了我如何使用 sed 在 shell 上进行替换

[root@server dir]# cat mystackconf.conf
>>first="one"
>>second="two"
>>third="four"

[root@server dir]# sed 's/\(^third=\).*/\1"three"/' mystackconf.conf
>>first="one"
>>second="two"
>>third="three"

我创建了一段非常草率的 Python 代码来完成这项工作(在使用 subprocess 模块时调用 sed 命令)

STACK.PY

import subprocess

conf = '/var/tmp/dir/mystackconf.conf'
mydict = {"first": "one", "second": "two", "third": "three"}

for key, value in mydict.iteritems():
    subprocess.Popen(
        "/bin/sed -i 's/\(^%s=\).*/\\1\"%s\"/' %s" % (key, value, conf),
        shell=True, stdout=subprocess.PIPE).stdout.read()

有没有更简洁的方法来使用 python re 模块或用通配符替换字符串?我对正则表达式很陌生,所以我不知道如何尝试。

[root@server dir]# cat mystackconf.conf 
>>first="one"
>>second="two"
>>third="four"

[root@server dir]# python stack.py

[root@server dir]# cat mystackconf.conf 
>>first="one"
>>second="two"
>>third="three"

这是我想象中的一个非常非常糟糕的尝试:

STACK.PY

conf = '/var/tmp/dir/mystackconf.conf'
mydict = {"first": "one", "second": "two", "third": "three"}

with open(conf, 'a') as file:
    for key, value in mydict.iteritems():
        file.replace('[%s=].*' % key, '%s=%s' % (key, value))

【问题讨论】:

  • 你想用字符串“three”替换字符串“four”的每个实例吗?
  • 不 - 只是 key = "third" 的值应该设置为 "three" - 但这会遍历字典,所以对于字典中的每个键,如果以 '%s=' % 键开头的配置文件,然后将 替换为字典中的值

标签: python regex bash python-2.7 sed


【解决方案1】:

Python 有一个名为 ConfigParser 的内置模块可以做到这一点:https://docs.python.org/2/library/configparser.html

或者你可以使用re 类似这样的东西:

conf = '/var/tmp/dir/mystackconf.conf'
mydict = {"first": "one", "second": "two", "third": "three"}

lines = []
with open(conf) as infile:
    for line in infile:
        for key, value in mydict.iteritems():
            line = re.sub('^{}=.*'.format(key), '{}={}'.format(key, value), line.strip())
        lines.append(line)

with open(conf, 'w') as outfile:
    for line in lines:
        print >>outfile, line

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多