[英]python ConfigParser: read configuration from string
I would like to parse a configuration string that I receive from a service and read each single paramenter. 我想解析一个从服务接收的配置字符串,并读取每个参数。 The string result is
[section 1],var1 = 111,var2 = 222
字符串结果为
[section 1],var1 = 111,var2 = 222
My code: 我的代码:
#!/usr/bin/python
import ConfigParser
import io
[...]
result = decoded['result']
result = result.replace(',', '\n');
print result
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(result))
print config.get("section 1", "var2")
print config.get("section 1", "var1")
using: 使用:
res = """
[section 1]
var1 = 111
var2 = 222
"""
it works so I believe is something wrong with result.replace(',', '\\n');
它有效,所以我相信
result.replace(',', '\\n');
出了点问题result.replace(',', '\\n');
but if I print the result seems good. 但是如果我打印的结果看起来不错。 Any suggestion please?
有什么建议吗?
Thank you dk 谢谢dk
This should work. 这应该工作。 It was an unicode error.
这是一个unicode错误。 Next time please show the stack trace
下次请显示堆栈跟踪
result = u"""
[section 1]
var1 = 111
var2 = 222
"""
print repr(result)
config = ConfigParser.ConfigParser(allow_no_value=True)
config.readfp(io.StringIO(result))
print config.get("section 1", "var2")
print config.get("section 1", "var1")
output: 输出:
u'\n[section 1]\nvar1 = 111\nvar2 = 222\n'
222
111
There is a method for this called read_string
on the ConfigParser
object. ConfigParser
对象上有一个称为read_string
的方法。
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read_string(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.