![](/img/trans.png)
[英]How to insert a space before and after a character and put on a new line in Python?
[英]Make python configobj to not put a space before and after the '='
簡單的問題。 是否可以使configobj在配置條目中的'='之前和之后不留空格?
我正在使用configobj讀取和寫入一個文件,該文件隨后由bash腳本處理,因此放置一個如下的antry:
VARIABLE =“值”
破壞bash腳本,它必須始終是:
VARIABLE = “值”
或者,如果有人對如何使用此類條目(和限制)讀寫文件有其他建議,也可以。
謝謝
我正在通過更改1980行來調查相同和修改的configobj.py :
def _write_line(self, indent_string, entry, this_entry, comment)
從:
self._a_to_u(' = ')
至:
self._a_to_u('=')
更改后,輸出的等號前后沒有空格。
Configobj用於讀取和寫入ini樣式的配置文件。 您顯然正在嘗試使用它編寫bash腳本。 那是行不通的。
只需按照自己的意願編寫bash腳本即可,也許使用模板或其他方式。
為了使ConfigParses不在=
周圍寫空格,可能需要將其子類化。 我猜想您必須修改write方法,但是只有閱讀代碼才能有所幫助。 :-)
好了,正如建議的那樣,我最終為此編寫了自己的解析器,可以與ConfigObj完全相同地使用它:
config = MyConfigParser("configuration_file")
print config["CONFIG_OPTION_1"]
config["CONFIG_OPTION_1"]= "Value 1"
print config["CONFIG_OPTION_1
config.write()
如果有人感興趣或想提出建議,這就是代碼(我不久前開始使用python進行編碼,因此可能還有很多改進的空間)。 它尊重注釋和文件中選項的順序,並正確地進行轉義,並在需要時添加雙引號:
import os
import sys
class MyConfigParser:
name = 'MyConfigParser'
debug = False
fileName = None
fileContents = None
configOptions = dict()
def __init__(self, fileName, debug=False):
self.fileName = fileName
self.debug = debug
self._open()
def _open(self):
try:
with open(self.fileName, 'r') as file:
for line in file:
#If it isn't a comment get the variable and value and put it on a dict
if not line.startswith("#") and len(line) > 1:
(key, val) = line.rstrip('\n').split('=')
val = val.strip()
val = val.strip('\"')
val = val.strip('\'')
self.configOptions[key.strip()] = val
except:
print "ERROR: File " + self.fileName + " Not Found\n"
def write(self):
try:
#Write the file contents
with open(self.fileName, 'r+') as file:
lines = file.readlines()
#Truncate file so we don't need to close it and open it again
#for writing
file.seek(0)
file.truncate()
i = 0
#Loop through the file to change with new values in dict
for line in lines:
if not line.startswith("#") and len(line) > 1:
(key, val) = line.rstrip('\n').split('=')
try:
if key in line:
newVal = self.configOptions[key]
#Only update if the variable value has changed
if val != newVal:
newLine = key + "=\"" + newVal + "\"\n"
line = newLine
except:
continue
i +=1
file.write(line)
except IOError as e:
print "ERROR opening file " + self.fileName + ": " + e.strerror + "\n"
#Redefinition of __getitem__ and __setitem__
def __getitem__(self, key):
try:
return self.configOptions.__getitem__(key)
except KeyError as e:
if isinstance(key,int):
keys = self.configOptions.keys()
return self.configOptions[keys[key]]
else:
raise KeyError("Key " +key+ " doesn't exist")
def __setitem__(self,key,value):
self.configOptions[key] = value
如上所述,可以通過對_write_line方法進行少量更改來刪除等號兩側的空格。 可以通過子類化ConfigObj並覆蓋_write_line來方便地完成此操作,如下所示-
from configobj import ConfigObj
class MyConfigObj(ConfigObj):
def __init__(self, *args, **kwargs):
ConfigObj.__init__(self, *args, **kwargs)
def _write_line(self, indent_string, entry, this_entry, comment):
"""Write an individual line, for the write method"""
# NOTE: the calls to self._quote here handles non-StringType values.
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
val = repr(this_entry)
return '%s%s%s%s%s' % (indent_string,
self._decode_element(self._quote(entry, multiline=False)),
self._a_to_u('='),
val,
self._decode_element(comment))
然后只需使用MyConfigObj代替ConfigObj,即可維護ConfigObj的所有功能
正如Lennart所建議的那樣,configobj可能不是工作的正確工具:如何:
>>> import pipes
>>> def dict2bash(d):
... for k, v in d.iteritems():
... print "%s=%s" % (k, pipes.quote(v))
...
>>> dict2bash({'foo': "bar baz quux"})
foo='bar baz quux'
由於configobj返回的內容看起來很像字典,因此您可能仍可以使用它來讀取您要處理的數據。
首先,感謝胡安喬。 那就是我想要的。 但是我稍微編輯了ConfigParser。 現在,它可以處理以下形式的bash腳本數組:
# Network interfaces to be configured
ifaces=( "eth0" "eth1" "eth2" "eth3" )
如果設置了一個值,它只會證明一個值是否為列表,如果是,它將正確設置引號。 因此,即使是列表,您也可以以相同的方式設置值:
ifaces = ['eth0', 'eth1', 'eth2', 'eth3']
conf['ifaces'] = ifaces
這是代碼:
import os
import sys
class MyConfigParser:
name = 'MyConfigParser'
debug = False
fileName = None
fileContents = None
configOptions = dict()
qouteOptions = dict()
def __init__(self, fileName, debug=False):
self.fileName = fileName
self.debug = debug
self._open()
def _open(self):
try:
with open(self.fileName, 'r') as file:
for line in file:
#If it isn't a comment get the variable and value and put it on a dict
if not line.startswith("#") and len(line) > 1:
(key, val) = line.rstrip('\n').split('=')
val = val.strip()
val = val.strip('\"')
val = val.strip('\'')
self.configOptions[key.strip()] = val
if val.startswith("("):
self.qouteOptions[key.strip()] = ''
else:
self.qouteOptions[key.strip()] = '\"'
except:
print "ERROR: File " + self.fileName + " Not Found\n"
def write(self):
try:
#Write the file contents
with open(self.fileName, 'r+') as file:
lines = file.readlines()
#Truncate file so we don't need to close it and open it again
#for writing
file.seek(0)
file.truncate()
#Loop through the file to change with new values in dict
for line in lines:
if not line.startswith("#") and len(line) > 1:
(key, val) = line.rstrip('\n').split('=')
try:
if key in line:
quotes = self.qouteOptions[key]
newVal = quotes + self.configOptions[key] + quotes
#Only update if the variable value has changed
if val != newVal:
newLine = key + "=" + newVal + "\n"
line = newLine
except:
continue
file.write(line)
except IOError as e:
print "ERROR opening file " + self.fileName + ": " + e.strerror + "\n"
#Redefinition of __getitem__ and __setitem__
def __getitem__(self, key):
try:
return self.configOptions.__getitem__(key)
except KeyError as e:
if isinstance(key,int):
keys = self.configOptions.keys()
return self.configOptions[keys[key]]
else:
raise KeyError("Key " + key + " doesn't exist")
def __setitem__(self, key, value):
if isinstance(value, list):
self.qouteOptions[key] = ''
value_list = '('
for item in value:
value_list += ' \"' + item + '\"'
value_list += ' )'
self.configOptions[key] = value_list
else:
self.qouteOptions[key] = '\"'
self.configOptions[key] = value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.