poj*_*ojo 77 python configuration-files python-2.x configparser
我曾尝试使用Python的ConfigParser模块来保存设置.对于我的应用程序,重要的是我在我的部分中保留每个名称的大小写.文档提到将str()传递给ConfigParser.optionxform()会实现这一点,但它对我不起作用.名称都是小写的.我错过了什么吗?
<~/.myrc contents>
[rules]
Monkey = foo
Ferret = baz
Run Code Online (Sandbox Code Playgroud)
我获得的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')]
Run Code Online (Sandbox Code Playgroud)
Mar*_*wis 99
文档令人困惑.他们的意思是:
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')
Run Code Online (Sandbox Code Playgroud)
即覆盖optionxform,而不是调用它; 覆盖可以在子类或实例中完成.覆盖时,将其设置为函数(而不是调用函数的结果).
uli*_*der 27
对于我来说,在创建对象后立即设置了optionxform
config = ConfigParser.RawConfigParser()
config.optionxform = str
Run Code Online (Sandbox Code Playgroud)
我知道这个问题得到了回答,但我认为有些人可能会发现这个解决方案很有用。这是一个可以轻松替换现有ConfigParser类的类。
编辑以纳入@OozeMeister 的建议:
class CaseConfigParser(ConfigParser):
def optionxform(self, optionstr):
return optionstr
Run Code Online (Sandbox Code Playgroud)
用法和正常一样ConfigParser。
parser = CaseConfigParser()
parser.read(something)
Run Code Online (Sandbox Code Playgroud)
这样你就可以避免optionxform每次创建 new 时都必须设置ConfigParser,这有点乏味。
添加到您的代码:
config.optionxform = lambda option: option # preserve case for letters
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25147 次 |
| 最近记录: |