我正在尝试使用类似于sed -i
的就地值更改来更新配置文件的“值”部分。
下面的代码展示了如何使用sed
[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代码来完成工作(使用sed
模块调用subprocess
命令)
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))
答案 0 :(得分:2)
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