python等于号前后一定要加空格吗_使python configobj在'='前后不放置空格

首先,感谢Juancho。这就是我一直在寻找的。但是我编辑了一下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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值