我是python的新手。如何从cfg文件中检索键值对
我有一个配置文件,如下所示,在相同的顺序。我需要检索从配置文件键,值对,将在我的脚本
# Name and details
(
{ group => 'abc',
host => 'pqr.com',
user => 'anonymous',
src => '/var/tmp',
dest => '/tmp',
},
{ group => 'abc',
host =>'pqr.com',
user => 'anonymous',
src => '/tmp'
dest => '/var/tmp'
},
{ group => 'pqr',
host =>'abc.com',
user => 'xyz',
src => '/home/pp',
dest => '/var/tmp',
},
{ group => 'xyz',
host =>'p.com',
user => 'x',
src => '/home/',
dest => '/tmp',
}
)使用这些值
每个
{
}
是considerd作为一个块.. Group
,user
, host
是独特的以及重复。 我必须阅读和解析配置文件,并显示键和值对。请帮助。
Key : group,Value : 'abc'(say)
key : host ,Value :'pqr.com'
Key : user, Value :'anonymous'
Key : src,Value :'/var/tmp',
key : dest,Value : '/tmp'
谢谢
我已经写,其显示的键和值服用CFG文件(如上所示)作为输入的代码。
idx = 0
dictList = []
while True:
try:
start = config.index("{", idx)
end = config.index("}", start+1)
slice = config[start+1:end-1]
sliceList = [s.strip() for s in slice.split(",") if s.strip()]
dd = {}
for item in sliceList:
key, value = [s.strip() for s in item.split("=>")]
print key, value
输出同时显示键,值
key 'value'
group 'abc'
host 'pqr.com'
user 'ananymous'
src '/use/tmp
现在的问题是,如何显示对应于键的值。 例如:打印组 - 应显示abc 打印主机应显示pqr.com,等等。
是这样的组'abc'是在配置文件中还是部分重复在这里? – 2012-04-28 15:29:51
嗨,它是在配置文件中... – ags 2012-04-29 02:30:50