2017-08-08 34 views
1

我試圖使用類似於sed -i的就地值更改來更新配置文件的「值」部分。Python就地配置值更新

下面的代碼顯示瞭如何會做使用外殼上的更換sed

[[email protected] dir]# cat mystackconf.conf 
>>first="one" 
>>second="two" 
>>third="four" 

[[email protected] 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() 

爲Th在python re模塊或者用通配符替換字符串的時候可以使用更簡潔的方法嗎?我對正則表達式很陌生,所以我不知道如何進行嘗試。

[[email protected] dir]# cat mystackconf.conf 
>>first="one" 
>>second="two" 
>>third="four" 

[[email protected] dir]# python stack.py 

[[email protected] 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

是否要將字符串「four」的每個實例替換爲字符串「three」? – marcusshep

+0

Nope - 只要key =「third」的值應該設置爲「three」 - 但是這會遍歷字典,因此對於字典中的每個鍵,如果在配置文件中有一個字符串以'%'開頭, s = '%key然後用字典中的值替換 AK47

回答

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