在 ConfigParser 中保留大小写?

发布于 2024-08-08 21:05:30 字数 802 浏览 3 评论 0原文

我尝试使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

别挽留 2024-08-15 21:05:30

文档很混乱。他们的意思是这样的:

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')

即覆盖 optionxform,而不是调用它;重写可以在子类或实例中完成。重写时,将其设置为函数(而不是调用函数的结果)。

我现在已报告这是一个错误,并且已修复。

The documentation is confusing. What they mean is this:

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')

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.

孤独难免 2024-08-15 21:05:30

对我来说,在创建对象后立即设置 optionxform

config = ConfigParser.RawConfigParser()
config.optionxform = str

For me worked to set optionxform immediately after creating the object

config = ConfigParser.RawConfigParser()
config.optionxform = str
小梨窩很甜 2024-08-15 21:05:30

添加到您的代码:

config.optionxform = lambda option: option  # preserve case for letters

Add to your code:

config.optionxform = lambda option: option  # preserve case for letters
白龙吟 2024-08-15 21:05:30

我知道这个问题已经得到解答,但我认为有些人可能会发现这个解决方案很有用。该类可以轻松替换现有的 ConfigParser 类。

编辑以纳入 @OozeMeister 的建议:

class CaseConfigParser(ConfigParser):
    def optionxform(self, optionstr):
        return optionstr

用法与普通 ConfigParser 相同。

parser = CaseConfigParser()
parser.read(something)

这样您就可以避免每次创建新的 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:

class CaseConfigParser(ConfigParser):
    def optionxform(self, optionstr):
        return optionstr

Usage is the same as normal ConfigParser.

parser = CaseConfigParser()
parser.read(something)

This is so you avoid having to set optionxform every time you make a new ConfigParser, which is kind of tedious.

随遇而安 2024-08-15 21:05:30

注意:

如果您使用 ConfigParser 的默认值,即:

config = ConfigParser.SafeConfigParser({'FOO_BAZ': 'bar'})

然后尝试使用以下方法使解析器区分大小写:

config.optionxform = str

配置文件中的所有选项将保留其大小写,但 FOO_BAZ 将是转换为小写。

要让默认值也保持其大小写,请像 @icedtrees 答案中那样使用子类化:

class CaseConfigParser(ConfigParser.SafeConfigParser):
    def optionxform(self, optionstr):
        return optionstr

config = CaseConfigParser({'FOO_BAZ': 'bar'})

现在 FOO_BAZ 将保持其大小写,并且您不会遇到 InterpolationMissingOptionError

Caveat:

If you use defaults with ConfigParser, i.e.:

config = ConfigParser.SafeConfigParser({'FOO_BAZ': 'bar'})

and then try to make the parser case-sensitive by using this:

config.optionxform = str

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:

class CaseConfigParser(ConfigParser.SafeConfigParser):
    def optionxform(self, optionstr):
        return optionstr

config = CaseConfigParser({'FOO_BAZ': 'bar'})

Now FOO_BAZ will keep it's case and you won't have InterpolationMissingOptionError.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文