在 ConfigParser 中保留大小写?
我尝试使用Python的 ConfigParser 模块来保存设置。对于我的应用程序,保留部分中每个名称的大小写非常重要。文档提到将 str() 传递给 ConfigParser.optionxform() 可以实现这一点,但它对我不起作用。名字都是小写的。我错过了什么吗?
<~/.myrc contents>
[rules]
Monkey = foo
Ferret = baz
我得到的Python伪代码:
import ConfigParser,os
def get_config():
config = ConfigParser.ConfigParser()
config.optionxform(str())
try:
config.read(os.path.expanduser('~/.myrc'))
return config
except Exception, e:
log.error(e)
c = get_config()
print c.options('rules')
[('monkey', 'foo'), ('ferret', 'baz')]
I have tried to use Python's ConfigParser module to save settings. For my app it's important that I preserve the case of each name in my sections. The docs mention that passing str() to ConfigParser.optionxform() would accomplish this, but it doesn't work for me. The names are all lowercase. Am I missing something?
<~/.myrc contents>
[rules]
Monkey = foo
Ferret = baz
Python pseudocode of what I get:
import ConfigParser,os
def get_config():
config = ConfigParser.ConfigParser()
config.optionxform(str())
try:
config.read(os.path.expanduser('~/.myrc'))
return config
except Exception, e:
log.error(e)
c = get_config()
print c.options('rules')
[('monkey', 'foo'), ('ferret', 'baz')]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
文档很混乱。他们的意思是这样的:
即覆盖 optionxform,而不是调用它;重写可以在子类或实例中完成。重写时,将其设置为函数(而不是调用函数的结果)。
我现在已报告这是一个错误,并且已修复。
The documentation is confusing. What they mean is this:
I.e. override optionxform, instead of calling it; overriding can be done in a subclass or in the instance. When overriding, set it to a function (rather than the result of calling a function).
I have now reported this as a bug, and it has since been fixed.
对我来说,在创建对象后立即设置
optionxform
For me worked to set
optionxform
immediately after creating the object添加到您的代码:
Add to your code:
我知道这个问题已经得到解答,但我认为有些人可能会发现这个解决方案很有用。该类可以轻松替换现有的 ConfigParser 类。
编辑以纳入 @OozeMeister 的建议:
用法与普通 ConfigParser 相同。
这样您就可以避免每次创建新的
ConfigParser
时都必须设置optionxform
,这有点乏味。I know this question is answered, but I thought some people might find this solution useful. This is a class that can easily replace the existing
ConfigParser
class.Edited to incorporate @OozeMeister's suggestion:
Usage is the same as normal
ConfigParser
.This is so you avoid having to set
optionxform
every time you make a newConfigParser
, which is kind of tedious.注意:
如果您使用 ConfigParser 的默认值,即:
然后尝试使用以下方法使解析器区分大小写:
配置文件中的所有选项将保留其大小写,但
FOO_BAZ
将是转换为小写。要让默认值也保持其大小写,请像 @icedtrees 答案中那样使用子类化:
现在
FOO_BAZ
将保持其大小写,并且您不会遇到 InterpolationMissingOptionError。Caveat:
If you use defaults with ConfigParser, i.e.:
and then try to make the parser case-sensitive by using this:
all your options from config file(s) will keep their case, but
FOO_BAZ
will be converted to lowercase.To have defaults also keep their case, use subclassing like in @icedtrees answer:
Now
FOO_BAZ
will keep it's case and you won't have InterpolationMissingOptionError.